I'm new to mongoose and mongo, and I need some help. I'm attempting to duplicate existing documents in Mongo using node.js and mongoose.
My process for this is:
This works fine. The problem is that I need to have another document type, that holds an id as a reference to this type of document. In the success callback, the object passed in has no value for the '_id' field. This is where I'm attempting to grab it to save in the other document. But, when I check the database, the document was successfully saved and does in fact have an '_id'.
Can someone shed some light on what is going on here, or perhaps where I am misunderstanding this process.
Here is my code: In the Controller:
async.each(cards, function(card, nextCard) {¬
¬
var newCard = new Card(card);¬
newCard.story_id = story._id;¬
newCard.linkedElements = [];¬
¬
newCard._id = null;¬
delete newCard._id;¬
// The id has been removed to avoid¬
// duplicates in mongo.¬
¬
newCard.save(function(err, savedCard) {¬
¬
if (err) {¬
console.log('err', err);¬
process.exit();¬
}¬
// There were no errors.¬
¬
// The current card was duplicated.¬
¬
Element¬
.find({'card_id': card._id}, function(err, elements) {¬
¬
if (err) {¬
console.log('err', err);¬
process.exit();¬
}¬
// There were no errors.¬
¬
async.each(elements, function(element, nextElement) {¬
¬
var newElement = new Element();¬
¬
console.log('New card : ', newCard);¬
console.log('Saved card : ', savedCard);¬
¬
newElement.card_id = savedCard._id;¬
** I BELIEVE THIS IS THE PROBLEM! **
¬
newElement._id = null;¬
delete newElement._id;¬
// The id has been removed to avoid¬
// duplicates in mongo.
The Output from the console log and node:
New card : { story_id: 53f0e8f3c45582e00927a501,
rank: 1,
published: 'true',
__v: 0,
_id: null,
linkedElements: [] }
Saved card : { story_id: 53f0e8f3c45582e00927a501,
rank: 1,
published: 'true',
__v: 0,
_id: null,
linkedElements: [] }
POST /admin/stories/duplicate/53f0e4c1c973f73b08942591 200 18ms - 277b
err { [VersionError: No matching document found.] message: 'No matching document found.', name: 'VersionError' }
I wonder why it worked at all. When you call .save()
on mongoose
document it issue an update
operation sending only updated fields to MongoDB. It newer use MongoDB save
command, only insert
and update
.
Probably, mongoose only checks the status of insert
/update
operation.
I can see two options for you.
1. Remove _id
before calling new Card
constructor:
delete card._id;
var newCard = new Card(card);
or, if card
is a mongoose
document:
card_data = card.toObject();
delete card_data._id;
var newCard = new Card(card_data);
2. Set new _id
field instead of removing it:
newCard._id = new mongoose.Types.ObjectId();