1

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)

4 Answers4

2

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.

Taplar
  • 24,788
  • 4
  • 22
  • 35
2

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

collection.find({}, { projection: { _id: false } })
mrtnlrsn
  • 1,105
  • 11
  • 19
1

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});  
Mohammad Ali Rony
  • 4,695
  • 3
  • 19
  • 33
0

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

m90
  • 11,434
  • 13
  • 62
  • 112