'MongoDB object not updating
I am working on a database system using MongoDB. I am trying to save the current date and time, then update it if the same barcode on ID cards is scanned twice, thrice, etc... However, the $set will not update the item. I have already looked at MongoDB documentation and other Stack Overflow posts, but nothing seems to work. Other Stack Overflow posts suggested adding
{ new: true }
and
( overwrite: true }
I tried these both separately and in tandem neither worked.
My Code:
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!")
}
});
}
});
And my Schema:
var studentSchema = mongoose.Schema({
StudNum: String,
Attendance: Number,
LastDateTimeAttended: {
Year: Number,
Month: Number,
Day: Number,
Hours: Number,
Min: Number,
Sec: Number
}
});
Thanks in advance!
Edit: Just to clarify, saving the item works fine, but updating the item does not, also no errors are thrown while updating.
Solution 1:[1]
For those who don`t know the cause of the issue, it also may be that the variable is not declared in the scheme causing any alteration to be halted and ignored.
Solution 2:[2]
I suggest you try saving you date as a string.
LastDateTimeAttended in your model should expect a string, and new Student constructor should create LastDateTimeAttended variable by calling
let date = new Date();
LastDateTimeAttended = date.toString();
your new schema should look like
var studentSchema = mongoose.Schema({
StudNum: {type: String, required: true},
Attendance: {type: Number, required: true},
LastDateTimeAttended: {type: String, required: true}
});
you should then be able to update your mongodb document
Student.findOneandUpdate(conditions, update, callback). see working with mongoose Model.findOneandUpdate
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Luis Febro |
| Solution 2 | Tyler2P |
