Thursday, 8 June 2017

Mongoose save() not working after findById()

Given the following schema 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

  // look for car again in db
  db_car.findById(req.id).then(function(car){
    console.log('car from db', car); // this is not correct, returns old data, car in db has NOT been saved
  })
});

I am using Node.js, MongoDB and Mongoose.



via trs

No comments:

Post a Comment