Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
133 views
in Technique[技术] by (71.8m points)

javascript - Do something if nothing found with .find() mongoose

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

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');
    }
  });
});

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. :/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

or:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...