MongoDB via Mongoose JS - What is findByID?

后端 未结 4 1244
野趣味
野趣味 2020-12-04 13:01

I am writing a NodeJS server with ExpressJS, PassportJS, MongoDB and MongooseJS. I just managed to get PassportJS to use user data obtained via Mongoose to authenticate.

相关标签:
4条回答
  • 2020-12-04 13:25

    If the schema of id is not of type ObjectId you cannot operate with function : findbyId()

    0 讨论(0)
  • 2020-12-04 13:30

    findById is a convenience method on the model that's provided by Mongoose to find a document by its _id. The documentation for it can be found here.

    Example:

    // Search by ObjectId
    var id = "56e6dd2eb4494ed008d595bd";
    UserModel.findById(id, function (err, user) { ... } );
    

    Functionally, it's the same as calling:

    UserModel.findOne({_id: id}, function (err, user) { ... });
    

    Note that Mongoose will cast the provided id value to the type of _id as defined in the schema (defaulting to ObjectId).

    0 讨论(0)
  • 2020-12-04 13:42

    As opposed to find() which can return 1 or more documents, findById() can only return 0 or 1 document. Document(s) can be thought of as record(s).

    0 讨论(0)
  • 2020-12-04 13:44

    I'm the maintainer of Mongoose. findById() is a built-in method on Mongoose models. findById(id) is equivalent to findOne({ _id: id }), with one caveat: findById() with 0 params is equivalent to findOne({ _id: null }).

    You can read more about findById() on the Mongoose docs and this findById() tutorial.

    0 讨论(0)
提交回复
热议问题