【发布时间】:2021-12-04 02:01:23
【问题描述】:
我正在尝试使用 MongoDB 为 Express 应用设置通知。
我有一个 API 端点,我在 MongoDB 中的 readBy 字段中 $push 一个用户的 ID,以便在检索到用户的通知后将其“标记”为已读。当我向此端点发出请求时,它会返回 200 及其通知,但不会对 MongoDB 中的通知文档进行任何更新。 console.log回调中的查询响应给了我{ acknowledged: false }。根据Mongoose docs,acknowledged 是Boolean indicating everything went smoothly,但是关于acknowledged 是什么以及在查询/写入过程中的哪个时间点导致它发生的信息很少。由于它没有返回任何错误,我找不到解决问题的方法。
有人能解释一下acknowledged: false 到底是什么,通常是什么原因导致它,以及为什么它不会引发错误。
型号:
const notificationSchema = new Schema({
timestamp: {
type: Date,
required: true
},
type: {
type: String,
required: true,
enum: [
'newCustomer',
'contractSigned',
'invoicePaid',
'warrantyExp',
'assignedProject'
]
},
recipients: [{
type: Schema.Types.ObjectId,
ref: 'Employee',
required: true,
}],
customer: {
type: Schema.Types.ObjectId,
ref: 'Customer',
required: true,
},
readBy: [{
type: String
}],
uuid: {
type: String,
default: uuid.v4,
immutable: true,
required: true,
},
company: {
type: Schema.Types.ObjectId, ref: 'Company'
}
});
路线:
router.get("/notification/all", withAuth, async (req, res) => {
const FOURTEEN_DAYS = new Date().setDate(new Date().getDate() + 14);
try {
const { uuid, userId } = req.loggedInUser;
// Fetch notifications that have the user as a recipient.
Notification.find({
recipients: userId,
})
.populate("customer")
.exec((err, notifs) => {
if (err)
return res.status(500).json({
success: false,
message: "Error: Failed to retrieve notifications.",
});
const result = [];
const notifIds = [];
for (const notif of notifs) {
// Filter notif
result.push({
timestamp: notif.timestamp,
customer: notif.customer,
type: notif.type,
read: notif.readBy.includes(uuid),
});
// Add the user as read
notifIds.push(notif.uuid);
}
console.log(notifIds);
/* THIS RETURNS ACKNOWLEDGED: FALSE */
// Write to DB that user has read these notifications
Notification.updateMany(
{ uuid: { $in: notifIds } },
{ $push: { readBy: uuid } },
(err, resultUpdate) => {
if (err)
return res.status(500).json({
success: false,
message:
"Error: Failed to add check off notifications as read.",
});
console.log(resultUpdate);
// Delete notifications past 14 days and has been read by all recipients
Notification.deleteMany(
{
timestamp: { $gte: FOURTEEN_DAYS },
$expr: {
$eq: [{ $size: "$readBy" }, { $size: "$recipients" }],
},
},
(err) => {
if (err)
return res.status(500).json({
success: false,
message: "Error: Failed to delete old notifications.",
});
return res.status(200).json({
success: true,
notifications: result,
message: "Fetched notifications",
});
}
);
}
);
});
} catch (err) {
res.status(500).json({ success: false, message: err.toString() });
}
});
【问题讨论】:
标签: node.js mongodb express mongoose