Correct way to search for MongoDB entries by '_id' in Node

后端 未结 5 1763
野趣味
野趣味 2021-02-03 17:35

I\'m using MongoDb (as part of MongoJS) in Node. Here is the documentation for MongoJS.

I\'m trying to do a call within Node based

相关标签:
5条回答
  • 2021-02-03 18:09

    if you are using mongoose you can try this:

    var mongoose = require('mongoose')
    usersSchema = mongoose.model('users'),
    mongoose.Types.ObjectId("<object_id>")
    
    usersSchema.find({"_id": mongoose.Types.ObjectId("<object_id>")}, function (err, record) {
    // Do stuff
    });
    
    0 讨论(0)
  • 2021-02-03 18:16

    If you are using MongoJS, you can do:

    var ObjectId = mongojs.ObjectId;
    

    Then,

    db.users.find({"_id": ObjectId(id)}, function(err, user){...}
    
    0 讨论(0)
  • 2021-02-03 18:20

    You need to require the ObjectId function before using it:

    var ObjectId = require('mongodb').ObjectID;
    
    0 讨论(0)
  • 2021-02-03 18:21

    You can also destructure your ObjectId and MongoClient to optimize your code and make it more readable.

    const { MongoClient, ObjectId } = require('mongodb');
    
    0 讨论(0)
  • 2021-02-03 18:24

    Here's another way to utilise objectId when using mongoose.

    // at the top of the file
    const Mongoose = require('mongoose')
    const ObjectId = Mongoose.Types.ObjectId;
    
    // when using mongo to collect data
    Mongoose.model('users', userSchema).findOne({ _id: 
        ObjectId('xyz') }, function (err, user) {
            console.log(user)
            return handle(req, res)
        })
    })
    
    0 讨论(0)
提交回复
热议问题