Mika Mika - 2 months ago 10
Node.js Question

Mongoose not persisting returned object

Mongo: 3.2.1.

I have a model defined as such:

var MySchema = new Schema(
{
....
records: {type: Array, "default": []};


I first create an object based on that schema with no record field and it's correctly added to the database. I then update that object as such:

Client

angular.extend(this.object.records, [{test: 'test'}]);
this.Service.update(this.object);


Server (omitting the none-problematic code)

function saveUpdates(updates) {
return function(entity) {
var updated = _.merge(entity, updates);
return updated.save()
.then(updated => {
console.log(updated);
Model.find({_id: updated._id}).then((data)=> console.log(data));
return updated;
});
};
}


The first console.log prints the object with records field updated. The second prints the object without. What am I missing? How can the resolved promise be different than the persisted object? Shouldn't
data
and
updated
be identical?

Answer

I think you have a couple problems.

You are using the variable 'updated' twice.

var updated = _.merge(entity, updates);  // declared here
return updated.save()
  .then(updated => { // trying to re-declare here

The other issue might be that you are trying to merge the 'updates' property with the mongo object and not the actual object values. Try calling .toObject() on your mongo object to get the data.

function saveUpdates(updates) {
  return function(entity) {
    // call .toObject() to get the data values
    var entityObject = entity.toObject();
    // now merge updates values with the data values
    var updated = _.merge(entityObject, updates);
    // use findByIdAndUpdate to update
    // I added runValidators in case you have any validation you need
    return Model
      .findByIdAndUpdate(entity._id, updated, { 
        runValidators: true 
      })
      .exec()
      .then(updatedEntity => {
         console.log(updatedEntity);
         Model.find({_id: entity._id})
           .then(data => console.log(data));
      });
   }
}