MongoDB对象没有更新

问题描述 投票:1回答:2

我正在使用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
}
});

提前致谢!

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

javascript mongodb mongoose mongoose-schema
2个回答
1
投票

在你的情况下,我不确定它是你的找到并更新这是问题。我相信,因为你要更新的是一个嵌套对象,你需要在顶级属性前面添加它以获取mongoose来保存它。由于这些属性不存在于顶层,因此猫鼬只是扔掉它。

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

0
投票

我建议你尝试将日期保存为字符串。模型中的LastDateTimeAttended应该是一个字符串,新的Student构造函数应该通过调用创建LastDateTimeAttended变量

let date = new Date();
LastDateTimeAttended = date.toString();

你的新架构应该是这样的

var studentSchema = mongoose.Schema({
StudNum: {type: String, required: true},
Attendance: {type: Number, required: true},
LastDateTimeAttended: {type: String, required: true}
});

然后,您应该能够更新您的mongodb文档Student.findOneandUpdate(条件,更新,回调)。 see working with mongoose Model.findOneandUpdate

© www.soinside.com 2019 - 2024. All rights reserved.