1

我正在使用 MongoDB 开发数据库系统。我正在尝试保存当前日期和时间,然后如果身份证上的相同条形码被扫描两次、三次等,则更新它……但是,$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
}
});

提前致谢!

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

4

3 回答 3

1

对于那些不知道问题原因的人,也可能是未在方案中声明变量,导致任何更改被暂停和忽略。

于 2021-10-30T22:36:25.010 回答
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
    }
};
于 2018-09-02T07:10:43.170 回答
0

我建议您尝试将日期保存为字符串。 LastDateTimeAttended在您的模型中应该期望一个字符串,并且新的学生构造函数应该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(conditions, update, callback)请参阅使用 mongoose Model.findOneandUpdate

于 2018-09-02T07:36:14.350 回答