Reputation: 1333
I have a mongodb model called word, which has a mixed schema type variable called "appearance". Given a passed in array of words, I would like to store the list into the words collection. If the word already exist, check if the appearance field is different, and if so, push the corresponding lesson in the field, then save.
Where I'm having trouble is it is not saving correctly. I realise this is similar to the following problem, but I tried using xxx.markModified() but to no avail (Updating values in mongodb). Does anyone know how to solve it?
My schema is
word
-> appearance
-> word
//takes an array of words, and stores it in mongodb
function importWords(arr) {
arr.forEach(function(arrWord) {
Word.find({word: arrWord.word}, function(err, results) {
if(err) {
console.log('error');
return;
}
//entry doesn't exist yet
if(results.length === 0) {
Word.create(arrWord, function(err, result) {
console.log(result);
});
}
else {
var key = Object.keys(arrWord.appearance)[0],
lessons = arrWord.appearance[key];
//if the course is different, create a new entry
if (typeof results[0].appearance[key] === 'undefined') {
results[0].appearance[key] = lessons;
} else {
for (var i = 0, len = lessons.length; i < len; i++) {
//if the lesson is not in the current results, create an entry
if (results[0].appearance[key].indexOf(lessons[i]) === -1) {
results[0].appearance[key].push(lessons[i]);
} //end if statement
} //end for loop
} //end if-else statement
results[0].markModified('appearance');
results[0].save();
console.log(results[0])
console.log('***************');
}
})
})
}
var list = [
{ word: '我', appearance: { elementary_one_writing: [1, 8]
Upvotes: 1
Views: 2306
Reputation: 947
The save method is asynchronous, which means you can't be sure it has finished its work the way you write your code now. Use callbacks:
results[0].save( function(error){
if (error){
// augh!
}else{
console.log(results[0]); // <- yay! the document is definitely saved here
// ...
}
});
//console.log(results[0]); // <- no, we can't be sure results[0] is already saved in this line
Upvotes: 2