0

I don't understand why Mongoose find result references cannot be reassigned.

eg:

Ticket.findOne({_id: req.params.id}, (err, ticket) => {
    console.log("before: ", ticket)
    ticket.tasks = [1, 2] //won't work
    ticket.title = "foo"
    console.log("after: ", ticket)
    console.log("=========")
    let copyTicket = ticket.toObject()
    console.log("Solution after: ", copyTicket)
    copyTicket.tasks = [1, 2]
    copyTicket.title = "bar"
    console.log("Solution before: ", copyTicket)
})

Output

before:  { tasks: [],
  _id: 5aa17051e97eac407b72757a,
  title: 'ho'
  }
after:  { tasks: [],
  _id: 5aa17051e97eac407b72757a,
  title: 'foo',
  }
=========
Solution after:  { tasks: [],
  _id: 5aa17051e97eac407b72757a,
  title: 'foo',
  }
Solution before:  { tasks: [ 1, 2 ],
  _id: 5aa17051e97eac407b72757a,
  title: 'bar',
  }

Do you have any ideas how and why there is this behavior?

Julien Leray
  • 1,647
  • 2
  • 18
  • 34
  • Have you tried using calling the [**`lean()`**](http://mongoosejs.com/docs/api.html#query_Query-lean) method on the query chain? – chridam Mar 09 '18 at 09:13
  • Does that mean object returned by Mongoose are not plain js object? So why does a typeof answer Object, the console.log look exactly as a regular js object? I found this behavior really confusing! Plus modify primary type is working but not reference... – Julien Leray Mar 09 '18 at 09:19
  • 1
    Documents returned from Mongoose are not plain objects but model objects (Document) – chridam Mar 09 '18 at 10:08
  • @JulienLeray ofc a typeof gonna say it's an object, because it is. Console.log is calling the `toString()` method of the object and so display to you the pretty data. Now do a `Object.keys(ticket).forEach(x => console.log(ticket[x]));` you will see the mongoose additionnal keys – Orelsanpls Mar 09 '18 at 16:41

0 Answers0