如果没有发现 .find() mongoose 就做点什么 [英] Do something if nothing found with .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?
如果它没有找到它,它只是跳过 find 调用中的所有内容,这很好,除非我需要在之后做一些事情,如果它不存在我不想做的事情.:/
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屋!