Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 574
Lucien Perouze Avatar asked Dec 28 '17 21:12

Lucien Perouze


People also ask

Is Spread operator ES6?

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.

Does spread operator creates new object?

The fundamental idea of the object spread operator is to create a new plain object using the own properties of an existing object.

Does spread operator overwrite?

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.

What is Pread operator?

The JavaScript spread operator ( ... ) allows us to quickly copy all or part of an existing array or object into another array or object.


Video Answer


1 Answers

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.

like image 115
Tsvetan Ganev Avatar answered Oct 02 '22 14:10

Tsvetan Ganev