es6 spread operator - mongoose result copy
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.
Solution 1:
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.