Mehdi Hoseini
Mehdi Hoseini

Reputation: 415

Can not add property to an object in mongoose function

I have a function which gets some data from database and binds it to some variable:

exports.getAccDoc = function(req, res, send, next) {
var AccDoc = require('../models/accdoc');

AccDoc.find({
   startup_id: req.startup.startup_id
}).exec().then(function(accDocs) {
  vm.accDocs = accDocs; //I'm using vm in my view
  console.log(vm.accDocs); //logs a array that contains one object
  console.log(vm.accDocs[0]); //you know
  vm.accDocs[0].test = 'TEST'; //trying to add some property to the object
  console.log(vm.accDocs[0].test); //logs TEST like it should be
  console.log(vm.accDocs[0]); //logs an object, But it doesn't contain test property
  send(res); //sending vm to view
});
};

Why my object doesn't changes after adding test property to it?

(I can change existing values of a property though, But can not add new properties)

Upvotes: 4

Views: 800

Answers (1)

michelem
michelem

Reputation: 14590

That because the result returned from Mongoose is a Mongoose Object instead a plain javascript object. You need to use lean method to get the plain object you can play with.

AccDoc.find({
   startup_id: req.startup.startup_id
}).lean().exec().then(function(accDocs) {
  ...

Upvotes: 4

Related Questions