Flo
Flo

Reputation: 41

Cannot add property to mongoose find object

I am getting an object from the mongodb database and I would like to add an extra property to it before sending it to the frontend as a response (express).

obj = collection.find({});
obj[0].extra_property = "value";
res.send(obj);

I know that obj will also have some methods as properties (like $__version, increment, $__where, remove, delete ...) but the object received in the frontend only contains the properties I defined in the mongodb schema, without those methods and without my added extra_property.

Could you show me a better method of returning the object and explain to me why is this happening?

Upvotes: 0

Views: 708

Answers (1)

Tom Roman
Tom Roman

Reputation: 150

Using mongoose, you can do obj.toObject() which would give you a vanilla JS object. In your case:

obj = collection.find({});
let toSend = obj.toObject();
toSend.extra_property = "value";
res.send(toSend);

Upvotes: 4

Related Questions