Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using spread syntax with Mongoose Document after calling the .save method results in undefined keys

I'm using a Mongoose/MongoDB and I'm getting some odd behaviour when I try to use the spread syntax to return values from a document after I call .save() on it.

// Npc is a Mongoose schema
const npc = new Npc({
        ...input,
        creator: userId
      });

const createdNpc = await npc.save();

I have tried using the spead operator, but the name and description keys do not exist.

return {
          ...createdNpc
          creator: userFromId(npc.creator)
}

however when I access those values directly they ARE defined

return {
          description: createdNpc.description,
          name: createdNpc.name,
          creator: userFromId(npc.creator)
        };

I've made sure that the spelling of description and name are correct. I've tried logging both {...createdNpc} and {...createdNpc, description: createdNpc.description, name: createdNpc.name}. In the logs I've confirmed that name and description are both not defined (the keys don't exist) inside of {...createdNpc}

I have also tried logging createdNpc and {...createdNpc} and have confirmed that they return different values.

here's createdNpc:

{
  _id: 5d8d5c7a04fc40483be74b3b,
  name: 'NPC Name',
  description: 'My Postman NPC',
  creator: 5d8d50e0b5c8a6317541d067,
  __v: 0
}

it doesn't actually look like a Mongoose Document at all. I would post the result of {...createdNPC} to show the difference but it's a huge code snippet and I don't want to clutter the question. I'm happy to provide it if it will help!

I'm still very new to MongoDB & Mongoose. Why would using the spread syntax on a Mongoose Document change its value?

I don't think this should be relevant to the question but just in case I'll also mention this is for a graphql resolver.

like image 918
Brooklin Myers Avatar asked Dec 22 '22 21:12

Brooklin Myers


1 Answers

This is because Mongoose uses getters for all of its attributes. Before you use the spread operator, call createdNpc.toObject() to get a normal Object.

like image 114
jeffheifetz Avatar answered Dec 26 '22 01:12

jeffheifetz