Lucien Perouze
Lucien Perouze

Reputation: 650

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.

Upvotes: 56

Views: 15850

Answers (3)

Jha Nitesh
Jha Nitesh

Reputation: 388

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")


Upvotes: 3

zemil
zemil

Reputation: 5084

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

Upvotes: 0

Tsvetan Ganev
Tsvetan Ganev

Reputation: 8856

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.

Upvotes: 123

Related Questions