Check if ID exists in a collection with mongoose

前端 未结 5 976
無奈伤痛
無奈伤痛 2021-01-31 15:52

For instance, I have a collection User:

var mongoose = require(\'mongoose\');

var UserSchema = new mongoose.Schema({
    email: String,
    googleI         


        
5条回答
  •  终归单人心
    2021-01-31 16:39

    The accepted answer is fine for small collections.

    A faster way on larger collections is 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 feature to support what you (and I) want.


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

    Create an any.js file with this code:

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

提交回复
热议问题