I'm developping an express js API with mongo DB and mongoose.
I would like to create an object in Javascript es6 composed of few variables and the result of a mongoose request and want to do so with es6 spread operator :
MyModel.findOne({_id: id}, (error, result) => { if (!error) { const newObject = {...result, toto: "toto"}; } });
The problem is that applying a spread operator to result transform it in a wierd way:
newObject: { $__: { $options: true, activePaths: {...}, emitter: {...}, getters: {...}, ... _id: "edh5684dezd..." } $init: true, isNew: false, toto: "toto", _doc: { _id: "edh5684dezd...", oneFieldOfMyModel: "tata", anotherFieldOfMyModel: 42, ... } }
I kind of understand that the object result is enriched by mongoose to permit specific interactions with it but when I console.log before doing so it depict a simple object without all those things.
I would like not to cheat by doing ...result._doc because I abstract this part and it won't fit that way. Maybe there is a way to copy an object without eriched stuff.
Thank you for your time.
Note: Spread operator was introduced in ES6. Some browsers may not support the use of spread syntax. Visit JavaScript Spread Operator support to learn more.
The fundamental idea of the object spread operator is to create a new plain object using the own properties of an existing object.
Spread syntax allows us to utilize three periods to expand iterables such as arrays or objects and inherit the original iterable's values. In our case, we can use the spread operator to add on or overwrite additional style parameters.
The JavaScript spread operator ( ... ) allows us to quickly copy all or part of an existing array or object into another array or object.
You can use the Mongoose Document.toObject()
method. It will return the underlying plain JavaScript object fetched from the database.
const newObject = {...result.toObject(), toto: "toto"};
You can read more about the .toObject()
method here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With