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

后端 未结 10 1587
死守一世寂寞
死守一世寂寞 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条回答
  •  猫巷女王i
    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));
    
     });`
    

提交回复
热议问题