Ricky
Ricky

Reputation: 777

Mongo Find() function won't exclude _id

Hello I can't seem to get the exclude _id to work, here is the code

const findLabels = (db, cb) => {
  // Get the documents collection
  const collection = db.collection(documentName);

  // Find some documents
  collection.find({}, { _id: 0 }).toArray((err, docs) => {
    // An error occurred we need to return that to the given 
    // callback function
    if (err) {
      return cb(err);
    }

    assert.equal(err, null);
    console.log("Found the following records");
    console.log(docs)

    return cb(null, docs);
  });
}

Here is the output on the console log

Found the following records
[ { _id: 5a5ee78cc130e727a3b1fdb6, name: 'Downgradeklajds' },
  { _id: 5a5ee794c130e727a3b1fdb7, Pizel: '00:00:07' } ]

Where did I go wrong?

Upvotes: 16

Views: 23532

Answers (3)

adhg
adhg

Reputation: 10863

for newer version simply do:

collection.find({}, {_id: 0 })  

where find {} refers to all (no restrictions) and the next parameter is the projection so 0 or False excludes the _id (same for {_id: False } )

Upvotes: 12

weichao
weichao

Reputation: 3381

if you use findOne,

you can try

    const posts : Collection= db.collection('posts')
    let document = await posts.findOne({
            path: path
        }, {
            fields: {
                _id: 0
        }
    })

In example, I query path(used as _id)

Upvotes: 0

Lee
Lee

Reputation: 2992

I think the correct way to specify a projection is to use the "fields" or "projection" property, depends on the version of your driver.

collection.find({}, {projection:{ _id: 0 }})

Read documentation here.

Upvotes: 42

Related Questions