使用猫鼬检查集合中是否存在 ID [英] Check if ID exists in a collection with mongoose
问题描述
例如,我有一个集合 User
:
For instance, I have a collection 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
值.
What is the right way to just check if this id exists in the User
collection. I don't need it to read the file or return it, I just need the true
or false
value.
这是实现它的一种方法:
Here is one way to achieve it:
User.findOne({
_id: userID
}, function (err, existingUser) {
但是有没有更快更有效的方法?
推荐答案
使用 count
而不是 findOne.
Use count
rather than findOne.
这将(在幕后)导致猫鼬使用 find
:http://docs.mongodb.org/manual/reference/method/db.collection.count
This will (under the hood) cause mongoose to use find
: http://docs.mongodb.org/manual/reference/method/db.collection.count
findOne()
将读取并返回文档(如果存在)另一方面,find()
只返回一个游标(或不返回),并且只有在遍历游标时才读取数据.所以在我们的例子中,我们没有迭代游标,只是计算返回的结果.
findOne()
will read + return the document if it exists
On the other hand, find()
just returns a cursor (or not) and only reads the data if you iterate over the cursor.
So in our case, we're not iterating over the cursor, merely counting the results returned.
User.count({_id: userID}, function (err, count){
if(count>0){
//document exists });
}
});
这篇关于使用猫鼬检查集合中是否存在 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!