Skip to content Skip to sidebar Skip to footer

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

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.

Solution 2:

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

Post a Comment for "Es6 Spread Operator - Mongoose Result Copy"