Check if ID exists in a collection with mongoose

前端 未结 5 1013
無奈伤痛
無奈伤痛 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:29

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

    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)

提交回复
热议问题