skip to Main Content

I just saw a blog on how to retrive a particular document by the ID of the document but here the code just does not seem to work for some reason. It works always, can you people tell me why this is happening?

Code:

app.post('/api/get-list-data', (req, res) => {
    const listID = req.body.listID;

    client.connect(async err => {
        const collection = client.db('to-do-lists').collection('made');
        const data = await collection.findOne({ _id: new ObjectId() })

        if(data) {
            res.send(data);
        }
        else {
            res.send({ success: false });
        }
    })
})

Any help would be greatful!

4

Answers


  1. Chosen as BEST ANSWER

    I fixed my issue by getting the ObjectId in the top of the page like this:

    const { ObjectId } = require('mongodb');


  2. ObjectId is a global in mongo-cli but not in the node environment.
    You can use exported function ObjectId from the mongodb package to create a new ObjectId instance.

            const data = await collection.findOne({ _id: mongo.ObjectId() })
    

    You may also pass a valid hex representation of an objectID as an argument (assuming that listID is one)

            const data = await collection.findOne({ _id: mongo.ObjectId(listID) })
    

    You also need to import the mongodb package before using the statement above for this to work.

    const mongo = require('mongodb')
    
    Login or Signup to reply.
  3. Try to follow example:

    import { ObjectId } from "bson"
    
    app.post('/api/get-list-data', (req, res) => {
      const listID = req.body.listID;
      client.connect(async err => {
        const collection = client.db('to-do-lists').collection('made');
        const data = await collection.findOne({
          '_id': new BSON.ObjectId('3r6a9f26x')
        }).toArray();
        if (data) {
          res.send(data);
        } else {
          res.send({
            success: false
          });
        }
      })
    })
    

    Reference:

    Login or Signup to reply.
  4. I am using this library
    https://www.npmjs.com/package/bson-objectid

    #install
    npm install bson-objectid
    
    
    
    #EXAMPLES
    var ObjectID = require("bson-objectid");
    
    console.log(ObjectID());
    console.log(ObjectID("54495ad94c934721ede76d90"));
    console.log(ObjectID(1414093117));//time
    console.log(ObjectID([ 84, 73, 90, 217, 76, 147, 71, 33, 237, 231, 109, 144 ]));
    console.log(ObjectID(new Buffer([ 84, 73, 90, 217, 76, 147, 71, 33, 237, 231, 109, 144 ])));
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search