1

我有一个名为 word 的 mongodb 模型,它有一个名为“appearance”的混合模式类型变量。给定一个传入的单词数组,我想将列表存储到单词集合中。如果单词已经存在,则检查外观字段是否不同,如果不同,则在字段中推送相应的课程,然后保存。

我遇到麻烦的地方是它没有正确保存。我意识到这类似于以下问题,但我尝试使用 xxx.markModified() 但无济于事(更新 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]
4

1 回答 1

2

save方法是异步的,这意味着您不能确定它是否按照您现在编写代码的方式完成了工作。使用回调:

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
于 2013-10-12T11:30:49.657 回答