Mongoose: Confusion due to (proposed) spread operator on model instance

Created on 5 Jul 2016  Â·  8Comments  Â·  Source: Automattic/mongoose

See https://github.com/sebmarkbage/ecmascript-rest-spread for a description of the spread operator. It behaves much like Object.assign() and it iterates over the object's own properties.

When I use {...obj} on model instance, I don't get a copy of the plain object as I expected but instead a copy of all the mongoose internals.

So basically, it would be nice if that either worked, or if, in development at least, iterating over own properties would throw.

Most helpful comment

You can't. The spread operator always creates a new object, so you can't use it to update an existing object. Use Object.assign() as an alternative. Or, better yet, just use card.set(cardData), see Document#set()

All 8 comments

By design. Use doc.toObject() on the rhs of the spread operator. A mongoose doc doesn't really lend itself well to copying, too much syntactic sugar for change detection

@vkarpov15 Ok, so how about adding a getter to the mongoose doc that just throws when read? That way, no-one can do this by accident…

Can you clarify? I don't quite understand your comment.

Well, take a look at the log pane of http://www.webpackbin.com/EyjjHisIZ. Some getter could throw an error when something tries to make a straight copy of a mongoose document instead of using .toObject().

Possible, but not really worth the effort for a feature that isn't part of the ecmascript standard, especially since it would break things that iterate through a mongoose document's properties.

Right, makes sense, I didn't know if there was a legitimate reason for iterating through a mongoose doc.

      const card = await Card.findById(cardID);
      const newCardObject = { ...card.toObject(), ...cardData };
      let newMongooseCard: ICard = new Card(newCardObject);
      newMongooseCard.save(x=>{});

Here I get the error, that newMongooseCard has an attribute: _id .. which is not allowed for new Objects..but I try to update the card, which I found by ID... how to update an existing mongoose Object with the spread operator?

You can't. The spread operator always creates a new object, so you can't use it to update an existing object. Use Object.assign() as an alternative. Or, better yet, just use card.set(cardData), see Document#set()

Was this page helpful?
0 / 5 - 0 ratings

Related issues

gustavomanolo picture gustavomanolo  Â·  3Comments

adamreisnz picture adamreisnz  Â·  3Comments

efkan picture efkan  Â·  3Comments

Igorpollo picture Igorpollo  Â·  3Comments

ArThoX picture ArThoX  Â·  3Comments