'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:[1]
For someone it can be helpful:
const newObject = {
...JSON.parse(JSON.stringify(result)),
toto: "toto"
};
But there are restrictions if you use Dates, functions, undefined, regExp or Infinity within schema
Solution 2:[2]
I came across the same problem and found some alternatives apart from the previous answer.
Option 1 Object.assign():
The Object.assign() method copies all enumerable own properties from one or more source objects to a target object. It returns the modified target object.
example:
Object.assign(result, {toto: "toto");
Options 2 Document.prototype.set():
Sets the value of a path, or many paths.
doc.set("toto", "toto")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | zemil |
| Solution 2 | Jha Nitesh |
