我有一个名为word的mongodb模型,它有一个名为“appearance”的混合模式类型变量。鉴于传递的单词数组,我想将列表存储到单词集合中。如果单词已存在,请检查外观字段是否不同,如果是,请按字段中的相应课程,然后保存。
我遇到麻烦的地方是没有正确保存。我意识到这类似于以下问题,但我尝试使用xxx.markModified()但无效(Updating values in mongodb)。有谁知道如何解决它?
我的架构是
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]
答案 0 :(得分:2)
save方法是asynchronous,这意味着您无法确定它是否像您现在编写代码一样完成了工作。使用回调:
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