Reputation: 11628
So, i have a collection and a model for that collection, let's call it Post. I want to create an ordering mechanism, as you can see in the code.
var assignOrder = function(callback){
var donePosts = 0;
Post.find().sort({publishDate: 1}).exec(function(err, posts){
for(var i = 0; i < posts.length; i++){
var post = posts[i];
var previousPost = posts[i-1] || {};
var nextPost = posts[i+1] || {};
post.previousPost = previousPost.slug;
post.nextPost = nextPost.slug;
post.update(function(err, post, affected){
if(++donePosts === posts.length){
callback();
}
});
}
});
};
I don't understand why the posts aren't updated in the database.
I get the error: error: [MongoError: Mod on _id not allowed] but i'm not setting a new _id anywhere.
thanks
Upvotes: 0
Views: 109
Reputation: 312095
Use save
instead of update
to commit changes to a model instance.
var assignOrder = function(callback){
var donePosts = 0;
Post.find().sort({publishDate: 1}).exec(function(err, posts){
for(var i = 0; i < posts.length; i++){
var post = posts[i];
var previousPost = posts[i-1] || {};
var nextPost = posts[i+1] || {};
post.previousPost = previousPost.slug;
post.nextPost = nextPost.slug;
// Call save here, not update.
post.save(function(err, post, affected){
if(++donePosts === posts.length){
callback();
}
});
}
});
};
Upvotes: 1