node.js mongodb select document by _id node-mongodb-native

后端 未结 10 1490
死守一世寂寞
死守一世寂寞 2020-12-02 08:28

I\'m trying to select a document by id

I\'ve tried:

collection.update({ \"_id\": { \"$oid\": + theidID } }

collection.update({ \"_id\": theidID }

c         


        
相关标签:
10条回答
  • now you can just use this:

    var ObjectID = require('mongodb').ObjectID;
    var o_id = new ObjectID("yourObjectIdString");
    ....
    collection.update({'_id': o_id});
    

    You can see documentation here

    0 讨论(0)
  • 2020-12-02 08:58
    /* get id */
    const id        = request.params.id; // string "5d88733be8e32529c8b21f11"
    
    /* set object id */
    const ObjectId  = require('mongodb').ObjectID;
    
    /* filter */
    collection.update({ 
        "_id": ObjectId(id)
    } )
    
    0 讨论(0)
  • 2020-12-02 08:59

    This is what worked for me. Using mongoDB

    const mongoDB = require('mongodb')

    Then at the bottom where I am making my express get call.

    router.get('/users/:id', (req, res) => {
    const id = req.params.id;
    var o_id = new mongoDB.ObjectID(id);
    
    const usersCollection = database.collection('users');
    
    usersCollection.findOne({
      _id: o_id
    })
    
    .then(userFound => {
      if (!userFound){
        return res.status(404).end();
      }
      // console.log(json(userFound));
      return res.status(200).json(userFound)
    })
    .catch(err => console.log(err));
    
     });`
    
    0 讨论(0)
  • 2020-12-02 09:05

    I just used this code in Node.js app in controller file, and it works:

    var ObjectId = require('mongodb').ObjectId;
    ...
    User.findOne({_id:ObjectId("5abf2eaa1068113f1e")})
    .exec(function(err,data){
       // do stuff
    })
    

    do not forget to install "mongodb" before, and if you are using encryption of your passwords with bcrypt with "presave", be sure that you will not encrypt password after each modification of the record in DB.

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