我正在嘗試使用 MongoDB 為 Express 應用程式設定通知。
我有一個 API 端點,其中我$push將用戶的 id 輸入到readByMongoDB 中的欄位,以在檢索用戶的通知后將其“標記”為已讀。當我向這個端點發出請求時,它會回傳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() });
}
});
uj5u.com熱心網友回復:
從檔案:
該方法回傳一個包含以下內容的檔案:
- 如果操作以寫關注運行,則布林值被確認為真,如果寫關注被禁用,則為 false
- matchedCount 包含匹配檔案的數量
- modifiedCount 包含修改檔案的數量
- upsertedId 包含更新檔案的 _id
uj5u.com熱心網友回復:
所以事實證明這個問題與寫關注無關。acknowledged: false被回傳是因為我們試圖得到的值$push是undefined. 所以本質上 Mongoose 拒絕寫入undefined值,但不會因為輸入值未定義而引發錯誤。把它放在這里以防其他人遇到這個問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/375266.html
上一篇:在貓鼬中洗掉評論父母
下一篇:這個C語言陳述句是什么意思?
