2017-01-26 83 views
0

我有一个用户模式中存在记录更新单个属性看起来是这样的:猫鼬,如果数组

var userSchema = mongoose.Schema({ 
    ... 
    ask_history: [ 
      { 
       user_question_body: { 
        type: String 
       }, 
       favorite: { 
        type: Boolean, 
        default: false 
       }, 
       ask_time: { 
        type: Date, 
        default: Date.now 
       } 
      } 
     ] 
}) 

而且我现在的更新方法是这样的:

User.findOneAndUpdate({ 
     "_id": user_id, 
     ask_history.user_question_body: { 
      $ne: "an input string" 
     } 
    }, { 
     "$addToSet": { 
      ask_history: { 
       user_question_body: "an input string" 
      } 
     } 
    }, function(err, doc) { 
     if (err) 
      throw err; // handle error; 
     } 
    ); 

如何添加一个功能,例如,如果我准备好了具有{user_question_body:“输入字符串”}的ask_history数组中的记录,则将{ask_time}更新为当前更新时间。

回答

1

要更新的匹配文件的aks_time你应该使用$positional operator

User.findOneAndUpdate({ 
     "_id": user_id, 
     "ask_history.user_question_body": "an input string" 
    }, { 
     "$set": {"ask_history.$.ask_time": new Date()} 
    },{new:true, upsert: true}, function(err, doc) { 
     if (err) 
      throw err; // handle error; 
     } 
     console.log(doc) 
    ); 
+0

这仅更新新的日期到具有“ask_history.user_question_body”已有记载:“输入字符串”,但它不如果没有人创建记录? –

+0

请用'{new:true}'.E.g:'{new:true,upsert:true}'添加''upsert'“选项。 –