0

Given the following schema/structure for a car:

car : {
    _id: "123123",
    name: "Ferrari",
    owners: [
        {
            _id : "098098",
            active: true
        },
        {
            _id : "876876",
            active: true
        }
    ]
}

I want to change ALL owners.active to false

with the following code I am able to save the updated car object but it doesn't save to the database:

// find car by id
db_car.findById(req.id).then(function(car){
  car.owners.forEach(function(owner){
    owner.active = false;
  });
  car.save();
  console.log('updated car', car); // this is correct, shows updated data
});

// Now check database, data is not saved in the database!

I am using Node.js, MongoDB and Mongoose.

trs
  • 863
  • 2
  • 16
  • 35
  • `.save()` is an 'async' method. You are calling console log "before" the operation has actually completed. – Neil Lunn Jun 09 '17 at 09:40
  • @NeilLunn console log has nothing to do with the question. The question is "why `save()` doesn't work?" – trs Jun 10 '17 at 19:49

1 Answers1

0

Mongoose .findById() returns a query. Mongoose queries are not promises. Instead you can execute the query using .exec() which in turn returns a promise. For example:

db_car.findById(req.id).exec().then(function(car){ ...

Relevant piece of documentation: http://mongoosejs.com/docs/promises.html#queries-are-not-promises

ippi
  • 9,857
  • 2
  • 39
  • 50
  • I replaced the first line with yours but it still doesn't save to the database. – trs Jun 09 '17 at 19:24