如果找不到.find()mongoose,请做一些事情 [英] Do something if nothing found with .find() mongoose

查看:578
本文介绍了如果找不到.find()mongoose,请做一些事情的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm storing some data in a mongodb and accessing it with js/nodejs and mongoose. I can use .find() to find something in the database just fine, that isn't an issue. What is a problem is if there isn't something, I'd like to do something else. Currently this is what I'm trying:

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不在昵称索引中时,这些都不会触发。当发生这种情况时,我根本没有得到任何控制台,但我确实让user.nick在实际存在的情况下正常登录。我只是试着反过来这样做:

None of those fire when I do something where act.params wouldn't be in the nick index. I don't get anything to console at all when this happens, but I do get user.nick to log just fine when it's actually there. I just tried to do it in reverse like this:

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 。我在这里缺少什么?

but this still didn't log nope. What am I missing here?

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

If it doesn't find it, it just skips everything in the find call, which is fine, except I need to do things afterwards if it isn't there that I don't want to do if it is. :/

推荐答案

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

When there are no matches find() returns [], while findOne() returns null. So either use:

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
    }
}

这篇关于如果找不到.find()mongoose,请做一些事情的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆