NodeJs:如何为猫鼬查询响应JSON分配额外的对象



使用mongoose,我正在查询帖子列表,并希望通过向响应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,
}]
});

要为查询对象添加属性,你应该将它们转换为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);
});
}

because

Post.find()

不是返回一个对象,你可以设置prop isLiked为posts[index],但它是私有的。修复它的简单方法是使用lean()方法来获取返回对象

Post.find().lean()
.then(//do what you want)