MongoDB对象未更新

塞思·惠勒

我正在使用MongoDB开发数据库系统。我试图保存当前的日期和时间,然后将其更新(如果ID卡上的相同条形码被扫描两次,三次等)。但是,$ set不会更新该项目。我已经看过MongoDB文档和其他Stack Overflow帖子,但是似乎没有任何效果。其他Stack Overflow帖子建议添加

{ new: true }

( overwrite: true }

我分别尝试了这些方法,但都没有成功。

我的代码:

Student.findOne({StudNum: studNum}, function(err, studNumItem) {
   if (err) {
    res.send("MongoDB Error: " + err);
    return false;
   }
   if (!studNumItem) {
    var myData = new Student({ StudNum: studNum, Attendance : 1, LastDateTimeAttended : {
        Year: year, Month: month, Day: day, Hours: hours, Min: min, Sec: sec
    }});
    myData.save()
      .then(item => {
        res.send("saved to database: " + studNum + ", with attendance " + Attendance + "");
      })
      .catch(err => {
        res.send("unable to save to database: " + studNum + ", for attendance " + Attendance + "");
      });
    }
    else{
      var conditions = {StudNum: studNum};
      var update = {$inc : { Attendance: 1 }, $set : {
        "Year": year, "Month": month, "Day": day, "Hours": hours, "Min": min, "Sec": sec
      }};
      Student.findOneAndUpdate(conditions, update, { new: true }, function (err)
      {
          if (err) // If error
          {
            res.send(err);
          }
          else {
            res.send("Checked in!")
          }
      });
 }

});

和我的架构:

var studentSchema = mongoose.Schema({
StudNum: String,
Attendance: Number,
LastDateTimeAttended: {
  Year: Number,
  Month: Number,
  Day: Number,
  Hours: Number,
  Min: Number,
  Sec: Number
}
});

提前致谢!

编辑:只是为了澄清,保存项目工作正常,但更新项目却没有,更新时也不会引发任何错误。

内森·布兰德

就您而言,我不确定是不是您找到了这个问题并进行了更新。我相信,由于您要更新的对象是嵌套对象,因此您需要在其顶层添加顶级属性,以使猫鼬保存它。由于这些属性不存在于顶层,因此猫鼬只是将其丢弃。

var update = {$inc : { Attendance: 1 }, $set : {
    "LastDateTimeAttended.Year": year, "LastDateTimeAttended.Month": month, "LastDateTimeAttended.Day": day, "LastDateTimeAttended.Hours": hours, "LastDateTimeAttended.Min": min, "LastDateTimeAttended.Sec": sec
  }};

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章