Reputation: 409
I'm using the latest version of mongoose.
var question = new CodingQuestion(reqJSON);
question.save(function(err) {
if (err) console.log(err);
else{
var questionId = question.id;
console.log("successfully added question with id", questionId);
}
});
The new object can be saved successfully. The problem is that when I try to obtain the newly added object Id, the value I get is always off by one. For example, the value logged in console is "5356b2162f8a71c00ae48783" but the actual value in the database is "5356b2162f8a71c00ae48784". Any idea what may cause this problem?
Upvotes: 0
Views: 3496
Reputation: 91
We just ran into this issue. When you use the new
operator it will create an objectID in mongoose. This is ignored when you call .save()
where it will then use the next available objectID, hence it is off by one.
Upvotes: 0
Reputation: 5981
I think you are not getting the ID of the saved document. The anonymous function you pass the save
function takes two parameters, error
and saved_document
.
Try the following:
question.save(function(err, savedQuestion) {
if (err) console.log(err);
else{
var questionId = savedQuestion._id;
console.log("successfully added question with id", questionId);
}
});
Upvotes: 2