如果找不到.find()mongoose,请做一些事情

Rob*_*Rob 33 javascript mongoose mongodb node.js

我将一些数据存储在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);
    }
  });
});
Run Code Online (Sandbox Code Playgroud)

当我做一些act.params不会出现在缺口索引中时,这些都不会触发.当发生这种情况时,我根本没有得到任何控制台,但我确实让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');
    }
  });
});
Run Code Online (Sandbox Code Playgroud)

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

如果它没有找到它,它只是跳过查找调用中的所有内容,这很好,除非我之后需要做的事情,如果它不存在我不想做的话.:/

wei*_*yin 85

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

Model.find( {...}, function (err, results) {
    if (err) { ... }
    if (!results.length) {
        // do stuff here
    }
}
Run Code Online (Sandbox Code Playgroud)

要么:

Model.findOne( {...}, function (err, result) {
    if (err) { ... }
    if (!result) {
        // do stuff here
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这是解释`find()`和`findOne()`之间返回的差异并提供答案的答案! (7认同)

Rob*_*Rob 9

UserModel.find({ nick: act.params }, function (err, users) {
  if (err) { console.log(err) };
  if (!users.length) { //do stuff here };
  else {
    users.forEach(function (user) {
      console.log(user.nick);
    });
  }
});
Run Code Online (Sandbox Code Playgroud)

是我发现的工作.


小智 5

我不得不使用:

 if(!users.length) { //etc }
Run Code Online (Sandbox Code Playgroud)

让它工作.