使用貓鼬我正在查詢一個帖子串列,并想通過在回應 JSON 中添加一個布林值來確定用戶是否在查詢函式中喜歡該影像。我正在嘗試在 for 回圈中執行此操作。
但是,當我使用 console.log() 時,帶有該欄位的帖子會正確回傳,但不會將其修改為 JSON。
我的功能:
function(req, res) {
var isLiked, likeCount;
Post
.find(/* Params */)
.then(posts => {
for (var index in posts) {
posts[index].isLiked = posts[index].likes.includes(req.headers.userid)
console.log(posts[index]) // does not show 'isLiked' field in JSON
console.log(posts[index].isLiked) // response is correct
}
res.send(posts) // does not have 'isLiked field
})
},
發布架構:
var postSchema = new Schema({
userId: {
type: String,
required: true
},
caption: {
type: String,
required: false
},
likes: [{
type: String,
}]
});
uj5u.com熱心網友回復:
要將屬性添加到查詢物件,您應該將它們轉換為 JS 物件:
function getPosts(req, res) {
Post.find(/* Params */).then((posts) => {
const result = [];
for (const post of posts) {
const postObj = post.toObject();
postObj.isLiked = postObj.likes.includes(req.headers.userid);
result.push(postObj)
}
res.send(result);
});
}
uj5u.com熱心網友回復:
因為
Post.find()
不是回傳一個物件,你可以將 prop isLiked 設定為 posts[index] 但它是私有的。修復它的簡單方法是使用lea() 方法來獲取回傳物件
Post.find().lean()
.then(//do what you want)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/479933.html
