node.js 使用猫鼬检查集合中是否存在 ID

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27482806/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 18:13:52  来源:igfitidea点击:

Check if ID exists in a collection with mongoose

node.jsmongodbmongoose

提问by Michael

For instance, I have a collection User:

例如,我有一个集合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);

And then I have an ID:

然后我有一个ID:

var userID = "some-user-id"

What is the right way to just check if this id exists in the Usercollection. I don't need it to read the file or return it, I just need the trueor falsevalue.

仅检查User集合中是否存在此 id 的正确方法是什么。我不需要它来读取文件或返回它,我只需要trueorfalse值。

Here is one way to achieve it:

这是实现它的一种方法:

User.findOne({
     _id: userID
}, function (err, existingUser) {

But is there faster and more efficient way?

但是有没有更快更有效的方法呢?

回答by Alex

Use countrather than findOne.

使用count而不是 findOne。

This will (under the hood) cause mongoose to use find: http://docs.mongodb.org/manual/reference/method/db.collection.count

这将(在幕后)导致猫鼬使用findhttp: //docs.mongodb.org/manual/reference/method/db.collection.count

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.

findOne()将读取 + 返回文档(如果存在)另一方面,find()只返回一个游标(或不返回),并且只有在遍历游标时才读取数据。所以在我们的例子中,我们没有迭代游标,只是计算返回的结果。

User.count({_id: userID}, function (err, count){ 
    if(count>0){
        //document exists });
    }
}); 

回答by Tom

You can now use User.exists()as of September 2019like so:

User.exists()2019 年 9 月起,您现在可以像这样使用:

const doesUserExit = await User.exists({ _id: userID });

const doesUserExit = await User.exists({ _id: userID });

From the docs:

文档

Under the hood, MyModel.exists({ answer: 42 })is equivalent to MyModel.findOne({ answer: 42 }).select({ _id: 1 }).lean().then(doc => !!doc)

在引擎盖下,MyModel.exists({ answer: 42 })相当于 MyModel.findOne({ answer: 42 }).select({ _id: 1 }).lean().then(doc => !!doc)

回答by Alisson

The accepted answer is fine for small collections.

接受的答案适用于小型收藏。

A faster way on larger collectionsis to simply use this:

对大集合更快的方法是简单地使用:

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

It won't return all fields. I believe they are currently working on a new featureto support what you (and I) want.

它不会返回所有字段。我相信他们目前正在开发一项新功能来支持你(和我)想要的。



In the meantime you could create a plugin, very simple and reusable.

与此同时,您可以创建一个插件,非常简单且可重用。

Create an any.jsfile with this code:

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

Then in your model you do this:

然后在你的模型中你这样做:

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

...and use it like this:

...并像这样使用它:

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

回答by Hasan Sefa Ozalp

User.exists({ _id: userID }).then(exists => {
  if (exists) {
    res.redirect('/dashboard')
  } else {
    res.redirect('/login')
  }
})

More info can be found at Mongoose docs.

更多信息可以在Mongoose 文档中找到。