[英]How to make Mongoose throw an error when pulling an entry via findByIdAndUpdate() does not find anything in the db?
嗨,我是 mongodb 和 node.js 的新手。 我有以下縮寫模式:
const PostSchema = new Schema({
user: {
type: Schema.Types.ObjectId,
ref: 'user'
},
likes: [
{
user: {
type: Schema.Types.ObjectId,
ref: 'user'
}
}
],...
我想通過 id 訪問每個帖子(通過請求參數傳遞),然后根據用戶 id 刪除一個like。 目前,它會從數組中刪除類似的內容,但當我再次嘗試從數據庫中刪除相同的 id 時不會拋出任何錯誤。 這是我目前的代碼:
const like = await Post.findByIdAndUpdate(
req.params.id,
{ $pull: { likes: { user: req.user.id } } },
(error, result) => {
if (!error) {
return res.json('Post unliked');
}
return res.status(400).send('You have not liked this post');
}
);
使用 findById() 而不是 findByIdAndUpdate 找到正確的帖子,並使用更高階的 function map() 來訪問具有所需用戶屬性的特定索引。
await Post.findById(req.params.id, async (error, result) => {
if (!error) {
const index = result.likes
.map(like => {
return like.user;
})
.indexOf(req.user.id);
if (index > -1) {
console.log('found');
//was found
result.likes.splice(index, 1);
await result.save();
return res.json('Post unliked');
} else {
console.log('not found');
return res.status(400).send('You have not liked this post');
}
}
return res.json(error);
});
如果 Id 不存在,則返回 null 以便您檢查它是否返回 null 然后您可以發送狀態為 400 的響應,否則您可以發送狀態為 200 的響應。我認為這可以解決您的問題,希望它有效, 謝謝!
嘗試這樣的事情,如果它有效,請告訴我:
await Post.findByIdAndUpdate(
req.params.id, (error, result) => {
if (!error) {//if error
return res.json(error);
}
const index = result.likes.indexOf(`${req.user.id}` )//find the index, I am not sure if you will need to add it as a string, make some tests!
if (index > -1) {//was found
result.likes.splice(index, 1);//remove
result.save();//save the doc to mongo
return res.json('Post unliked');
}
else return res.status(400).send('You have not liked this post');// it was not found
}
);
您可能需要調整一些東西,因為我是從頭開始編寫代碼的!
我希望這會有所幫助!
參考:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.