我想知道如何在填充查询中获得计数,在这里仅获得填充数据计数,代码示例如下并输出
我使用猫鼬填充方法
exports.getPost = async (req, res) => {
try {
const user = await User.findOne({_id:req.params.user_id, status:1})
if(typeof user !== 'undefined' && user !== null){
const userPost = await User.find({_id:user._id, status:1},{_id:1,image:1,name:1})
.populate('positions',{_id:0,profile_name:1},{status:1})
.populate('posts',null,{status:1},{sort:{'createdAt':-1}}).exec(function(err, postData){
if(err){ console.log(err); }
async.forEach(postData, function(users, callback){
Post.populate(users.posts, {path: "comments", match:{status:1},select:{_id:1}}, function(err, comments){
if(err){ console.log(err); }
Post.populate(users.posts, {path: "likes", match:{like:true},select:{_id:1}}, function(err, likes){
if(err){ console.log(err); }
callback();
});
});
}, function(err){
res.status(200).json({
error: false,
message: "Post get successfully.",
users: postData
});
});
});
}else{
res.status(500).json({
error: true,
message: "Wrong user id"
});
}
} catch (e) {
helper.errorLogs("Get Post", "GET", req.protocol+'://'+req.get('host')+''+req.url, req.params.user_id, e.message, e.stack);
res.status(400).json({
error: true,
message: e.message
});
}
}
当前结果是:
{
"error": false,
"message": "Post get successfully.",
"users": [
{
"image": null,
"positions": [],
"posts": [
{
"comments": [
{
"_id": "5d71e288d2577012adb0675c"
},
{
"_id": "5d71e539e0c625171dde4a34"
}
],
"likes": [
{
"_id": "5d71f301697636220d73d339"
}
],
"status": 1,
"_id": "5d70f263c977a3579bd296a5",
"user_id": "5d70ecfd699c1056424218ff",
"post": "A morning could change that story entirely, though.",
"image": "https://honeycombapi.iapplabz.co.in/5mmid32qdff_1567766507302.jpeg",
"createdAt": "2019-09-05T11:32:51.981Z",
"updatedAt": "2019-09-06T10:41:47.307Z",
"__v": 4
}
],
"_id": "5d70ecfd699c1056424218ff",
"name": "anil"
}
]
}
,预期结果如下:
{
"error": false,
"message": "Post get successfully.",
"users": [
{
"image": null,
"positions": [ ],
"posts": [
{
"comments": "2",
"likes": "1",
"status": 1,
"_id": "5d70f263c977a3579bd296a5",
"user_id": "5d70ecfd699c1056424218ff",
"post": "A morning could change that story entirely, though.",
"image": "https://honeycombapi.iapplabz.co.in/5mmid32qdff_1567766507302.jpeg",
"createdAt": "2019-09-05T11:32:51.981Z",
"updatedAt": "2019-09-06T10:41:47.307Z",
"__v": 4
}
],
"_id": "5d70ecfd699c1056424218ff",
"name": "anil"
}
]
}