我有一個包含喜歡陣列的帖子集合。如果用戶不喜歡,我想將物件推送到喜歡陣列中,如果用戶喜歡帖子,我想拉取物件。我測驗我的 API,但它總是更新集合的第一個檔案,盡管我提供了postId其他檔案。
schema.js
likes: [
{
userId: String,
isNotified: {
type: Boolean,
default: false,
},
email: String,
types: String,
},
],
API
router.post("/like", (req, res) => {
postModel.find(
{
"_Id": req.body.postId,
"likes.userId": req.body.userId,
},
(err, doc) => {
// console.log(doc)
if (!doc.length) {
postModel.updateOne(
{ "_Id": req.body.postId,},
{
$push: {
likes: {
userId: req.body.userId,
email: req.body.email,
// types: req.body.types,
},
},
},
(err, doc) => {
res.send("like");
}
);
} else {
// console.log("pull")
postModel.find(
{
"_Id": req.body.postId,
"likes.userId": req.body.userId,
},
(err, doc) => {
doc.map((e) => {
e.likes.map((x) => {
if (x.userId == req.body.userId) {
postModel.updateOne(
{
"_Id": req.body.postId,
"likes.userId": req.body.userId,
},
{
$pull: {
likes: {
userId: req.body.userId,
email:req.body.email
},
},
},
(err, doc) => {
res.send("unlike");
}
);
}
});
});
}
);
}
// res.send(doc);
}
);
// });
});
郵遞員請求
{
"email":"[email protected]",
"types":"like",
"postId":"6312c2d1842444a707b6902f",
"userId":"631452d0e1c2acf0be28ce43"
}
如何解決這個問題,提出建議。在此先感謝。
uj5u.com熱心網友回復:
我不確定我是否理解邏輯,但這里有幾件事我認為你可以改進:
- 您正在使用
find方法來獲取單個檔案,您應該使用findOne回傳單個檔案(如果存在)而不是檔案陣列的方法。但一般來說,當你有_id檔案的價值時,最好只使用findById速度更快的方法。 - 當你
find是一個檔案時,你只需修改它并呼叫它的save方法將你的更改寫入資料庫,不需要使用updateOne. (請注意,部分更新有很多優點,但在您的情況下,它們似乎沒有必要,您可以在線閱讀。)
您的 API 代碼可能是這樣的:
router.post("/like", (req, res) => {
const postId = req.body.postId
const userId = req.body.userId
postModel.findById(postId) // get the post
.then(post => {
if (post) { // check if post exists
// check if user has already liked the post
if (post.likes.find(like => like.userId == userId)){
// user has already liked the post, so we want to
// remove it from likes (unlike the post).
// I know this is not the best way to remove an item
// from an array, but it's easy to understand and it
// also removes all duplications (just in case).
post.likes = post.likes.filter(like => like.userId != userId)
// save the modified post document and return
return post.save(_ => {
// send success message to client
res.send("unlike")
})
} else {
// user has not liked the post, so we want to add a
// like object to post's likes array
post.likes.push({
userId: userId,
email: req.body.email // you can other properties here
})
// save the modified post document and return
return post.save(_ => {
// send success message to client
res.send("like")
})
}
} else { // in case post doesn't exist
res.status(404).send("post not found.")
}
})
.catch(err => {
// you can handle errors here
console.log(err.message)
res.send("an error occurred")
})
})
我沒有運行代碼,但它應該可以作業。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/503988.html
