Benjamin AUBARBIER
Benjamin AUBARBIER

Reputation: 11

remove _id from the return of MongoDB

I have this.

app.get('/messages/all', async function (req, res) { 
const messages = await collection.find({}).toArray(); 
res.send(messages)

And i do this.

curl -X GET http://localhost:3000/messages/all

And this return this.

[{"_id":"5e973b8669e20600a59cd2b2","from":"user","msg":"ville"},{"_id":"5e973b8669e20600a59cd2b3","from":"bot","msg":"Nous sommes à Paris"}]

But i don't want the id. So i want to remove the _id.

Can i have help (i am not english and 19 dont judge me pls)

Upvotes: 1

Views: 2047

Answers (4)

mrtnlrsn
mrtnlrsn

Reputation: 1255

With nodejs and recent mongodb client (tested using 4.7.0), the syntax is:

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

Upvotes: 2

Mohammad Ali Rony
Mohammad Ali Rony

Reputation: 4915

You can add false like {"_id": false} MongoDB not to return _id from the collection

collection.find({},{"_id" : false}).toArray()

or you can use delete _id property from object javascript array

messages.forEach(function(v){ delete v._id});  

Upvotes: 1

Taplar
Taplar

Reputation: 24965

If collection.find({}) is a mongo call, then you can exclude the _id.

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

https://docs.mongodb.com/manual/reference/method/db.collection.find/

The second argument to the find is the projection.

Upvotes: 2

m90
m90

Reputation: 11822

In JavaScript, use the delete operator to remove a prop from an object:

let messages = collection.find({}).toArray()
messages = messages.map((doc) => {
  delete doc._id
  return doc
})

See: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Operators/delete

Upvotes: 0

Related Questions