例如,我有一个集合User
:
var mongoose = require('mongoose');
var UserSchema = new mongoose.Schema({
email: String,
googleId: String,
facebookId: String,
displayName: String,
active: Boolean
});
module.exports = mongoose.model('User', UserSchema);
然后我有一个ID:
var userID = "some-user-id"
检查User
集合中是否存在此ID的正确方法是什么。我不需要它来阅读文件或将其返回,我只需要true
或false
值。
这是实现它的一种方法:
User.findOne({
_id: userID
}, function (err, existingUser) {
但是有更快更有效的方法吗?
答案 0 :(得分:51)
使用count
而不是findOne。
这将导致猫鼬使用find
:http://docs.mongodb.org/manual/reference/method/db.collection.count
findOne()
将读取+返回文档
另一方面,find()
只返回游标(或不返回),只有在迭代游标时才读取数据。
所以在我们的例子中,我们不会迭代光标,只计算返回的结果。
User.count({_id: userID}, function (err, count){
if(count>0){
//document exists });
}
});
答案 1 :(得分:11)
您现在可以在 2019年9月使用 User.exists()
,如下所示:
const doesUserExit = await User.exists({ _id: userID });
来自docs:
在幕后,
MyModel.exists({ answer: 42 })
等效于MyModel.findOne({ answer: 42 }).select({ _id: 1 }).lean().then(doc => !!doc)
答案 2 :(得分:3)
可接受的答案适合小收藏。
在大型馆藏中更快的方法是简单地使用此方法:
const result = await User.findOne({ _id: userID }).select("_id").lean();
if (result) {
// user exists...
}
// or without "async/await":
User.findOne({ _id: userID }).select("_id").lean().then(result => {
if (result) {
// user exists...
}
});
它不会返回所有字段。我相信他们目前正在a new feature上工作,以支持您(和我)想要的东西。
同时,您可以创建一个非常简单且可重复使用的插件。
使用以下代码创建any.js
文件:
module.exports = function any(schema, options) {
schema.statics.any = async function (query) {
const result = await this.findOne(query).select("_id").lean();
return result ? true : false;
};
}
然后在模型中执行以下操作:
var mongoose = require('mongoose');
const any = require('./plugins/any'); // I'm assuming you created a "plugins" folder for it
var UserSchema = new mongoose.Schema({
email: String,
googleId: String,
facebookId: String,
displayName: String,
active: Boolean
});
UserSchema.plugin(any);
module.exports = mongoose.model('User', UserSchema);
...并像这样使用它:
const result = await User.any({ _id: userID });
if (result) {
// user exists...
}
// or without using "async/await":
User.any({ _id: userID }).then(result => {
if (result) {
// user exists...
}
});
答案 3 :(得分:0)
User.exists({ _id: userID }).then(exists => {
if (exists) {
res.redirect('/dashboard')
} else {
res.redirect('/login')
}
})
更多信息,请访问Mongoose docs。
答案 4 :(得分:0)
或者您可以简单地使用存在函数,而无需进行任何异步/等待:
myData = {_id: userID};
User.exists(myData,(error, result)=>{
if (error){
console.log(error)
} else {
console.log("result:", result) //result is true if myData already exists
}
});
您可以立即处理结果!