javascript - 如果 .find() mongoose 没有找到任何东西,请执行某些操作

我将一些数据存储在 mongodb 中,并使用 js/nodejs 和 mongoose 访问它。我可以使用 .find() 在数据库中找到一些东西就好了,这不是问题。问题是如果没有什么,我想做点别的。目前这是我正在尝试的:

UserModel.find({ nick: act.params }, function (err, users) {
  if (err) { console.log(err) };
  users.forEach(function (user) {
    if (user.nick === null) {
      console.log('null');
    } else if (user.nick === undefined) {
      console.log('undefined');
    } else if (user.nick === '') {
      console.log('empty');
    } else {
      console.log(user.nick);
    }
  });
});

当我执行 act.params 不在 nick 索引中的操作时,这些都不会触发。发生这种情况时,我根本没有得到任何安慰,但是当它实际存在时,我确实让 user.nick 记录得很好。我只是试着像这样反过来做:

UserModel.find({ nick: act.params }, function (err, users) {
  if (err) { console.log('noooope') };
  users.forEach(function (user) {
    if (user.nick !== '') {
      console.log('null');
    } else {
      console.log('nope');
    }
  });
});

但这仍然没有记录nope。我在这里错过了什么?

如果它没有找到它,它只会跳过 find 调用中的所有内容,这很好,但如果它不存在,我需要在之后做一些我不想做的事情。 :/

最佳答案

当没有匹配时 find() 返回 [],而 findOne() 返回 null。所以要么使用:

Model.find( {...}, function (err, results) {
    if (err) { ... }
    if (!results.length) {
        // do stuff here
    }
}

或:

Model.findOne( {...}, function (err, result) {
    if (err) { ... }
    if (!result) {
        // do stuff here
    }
}

https://stackoverflow.com/questions/9660587/

相关文章:

c# - Mongodb -- 使用 c# 驱动程序包含或排除某些元素

mongodb - 使用 $toLower 更新 MongoDB 集合

python - pymongo-如何为字段以及其他查询参数设置不同的值

mongodb - Spring数据MongoDb : MappingMongoConverter

mongodb - 使用 Mongo 集合中的特殊字符

python - 如何将 MongoDB 查询转换为 JSON?

mongodb - 使用mongodb在UTC中存储日期时如何处理时区问题?

mongodb - 如何在 MongoDB 中删除或删除集合?

mongodb - 为什么不用mongodb?

javascript - 如何在 MongoDB 中查询引用的对象?