Within my Meteor method, I have implemented a function to check for existing documents. If the document is not found, it gets inserted into the database. However, if it is found during a second attempt, the document is updated and a new one is also inserted. Could you please review and help me fix the code below:
'upload': function upload(data, name, eventId) {
const wb = XLSX.read(data, {type:'binary'});
var checkUpdate;
XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]).forEach(r => {
r.owner = this.userId,
r.username = Meteor.user().username,
r.updatedAt = new Date(),
r.amount = Number(r.amount),
r.eventid = eventId,
r.firstname = r.firstname.trim(),
r.lastname = r.lastname.trim(),
Registers.findOne({ firstname: r.firstname, lastname: r.lastname, eventid: eventId }) ?
Registers.update({ firstname: r.firstname, lastname: r.lastname, eventid: eventId }, { $set: {updatedAt: r.updatedAt, amount: r.amount } })
:
r.createdAt = new Date(),
Registers.insert(r)
})
return wb;
},
When the database is empty for the first time, a new document is inserted. On the second attempt, if a matching document is found, it gets updated, and a new document is inserted using the update operation instead of insertion.
meteor:PRIMARY> db.registers.find({ eventid: "aZrumf45q8sBGGrY2" })
{ "_id" : "MzqD73vsgyxRTyekJ", "salution" : "Mr.", "firstname" : "qwer", "lastname" : "asdf", ...
...
After running the code twice, I noticed that the 'createdAt' field was lost during the second instance. Can anyone explain why this happened?
I have figured it out now! Thank you so much for all your comments!
'upload': function upload(data, name, eventId) {
const wb = XLSX.read(data, {type:'binary'});
var checkUpdate;
XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]).forEach(r => {
if (!Registers.findOne({ firstname: r.firstname, lastname: r.lastname, eventid: eventId })) {
r.owner = this.userId,
r.username = Meteor.user().username,
r.updatedAt = new Date(),
r.amount = Number(r.amount),
r.eventid = eventId,
r.firstname = r.firstname.trim(),
r.lastname = r.lastname.trim(),
r.createdAt = new Date(),
Registers.insert(r)
} else {
r.owner = this.userId,
r.username = Meteor.user().username,
r.updatedAt = new Date(),
r.amount = Number(r.amount),
r.eventid = eventId,
r.firstname = r.firstname.trim(),
r.lastname = r.lastname.trim(),
Registers.update({ firstname: r.firstname, lastname: r.lastname, eventid: eventId }, { $set: {updatedAt: r.updatedAt, amount: r.amount } })
}
})
return wb;
},