我正在使用 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
}
});
提前致谢!
编辑:澄清一下,保存项目工作正常,但更新项目没有,更新时也不会抛出错误。
最佳答案
对于您的情况,我不确定是您的查找和更新问题。我相信由于您要更新的是嵌套对象,因此您需要在它前面加上顶级属性才能让 Mongoose 保存它。由于这些属性不存在于顶层, 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
}
};
关于javascript - MongoDB 对象不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52134709/