3

I am having trouble with mongoosejs, I think. I am trying to keep an array of objects at a specific size of 2. When this function is called it adds an item to the array and slims it down if necessary. However when I save the array the size is not trimmed down to 2. Follow the code and comments. Thanks for any help you can provide.

 user.location.push(req.body);  //Add a new object to the array.

    if(user.location.length > 2)  //If the array is larger than 2
      user.location.splice(0,1);   //Remove the first item

    console.log(user.location);  //This outputs exactly what I would expect.

    user.save(function(err, updatedUser){
      if(err)
        next(new Error('Could not save the updated user.'));
      else { 
        res.send(updatedUser);  //This outputs the array as if it was never spliced with a size greater than 2.
      }
    });
2
  • How is location defined in your schema? Commented Nov 12, 2012 at 20:08
  • just as an array "location: []" Commented Nov 12, 2012 at 20:17

1 Answer 1

8

Because you're defining location: [] in your schema, Mongoose treats that field as Mixed which means you have to notify Mongoose when you've changed it. See the docs here.

Change your code that updates user.location to be:

if(user.location.length > 2) {
  user.location.splice(0,1);
  user.markModified('location');
}
Sign up to request clarification or add additional context in comments.

2 Comments

This seems like it should have worked, but didn't. Any other ideas, or maybe this was just part of the problem. If I actually remove the first array in the element and save, then add an element to the array and save, it works 100% of the time.
object.markModified('objec_array_property') Worked for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.