【发布时间】:2016-10-14 00:45:18
【问题描述】:
我有一个看起来像这样的架构
var Post = new mongoose.Schema({
author: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
created: {
type: Date,
Default: Date.now
})
我也有一个用户表。我有一组用户 ID,我正在尝试根据一组用户 ID 搜索帖子表
举例
var userIds = ["575e96652473d2ab0ac51c1e","575e96652473d2ab0ac51c1d"] .... and so on
我想返回这些用户创建的所有帖子。帖子应按创建日期排序。有没有办法根据提供的用户 ID 对帖子进行分组,基本上匹配单个用户的帖子?
我想要达到的结果是这样的:
[{
userAId : "56656.....",
post : [postA, postB],
},{
userBId :"12345...",
post : [postA, postB]
}]
如何编写此查询?
这是我目前所拥有的
Post.aggregate([{
// {"$unwind" : ""},
// "$group": {
// _id: "$author",
// "created" : {"$sum" : 1 }
// }
"$match" : { author : id}
}]).exec(function(error, data) {
if(error){
return console.log(error);
}else{
return console.log(data)
}
})
{
"_id" : ObjectId("575e95bc2473d2ab0ac51c1b"),
"lastMod" : ISODate("2016-06-13T11:15:08.950Z"),
"author" : ObjectId("575dac62ec13010678fe41cd"),
"created" : ISODate("2016-06-13T11:15:08.947Z"),
"type" : "photo",
"end" : null,
"commentCount" : 0,
"viewCount" : 0,
"likes" : 0,
"tags" : [],
"title" : "Today is a good day",
"__v" : 0
}
【问题讨论】:
-
你能从 mongo 发布完整的帖子文档吗?
-
你的意思是发布整个帖子文档的架构吗??
-
db.post.findOne() 没问题 - 请删除敏感信息
-
"_id" : ObjectId("575e95bc2473d2ab0ac51c1b"), "lastMod" : ISODate("2016-06-13T11:15:08.950Z"), "author" : ObjectId("575dac62ec13010678fe41cd"), “创建”:ISODate(“2016-06-13T11:15:08.947Z”),“类型”:“照片”,“结束”:null,“commentCount”:0,“viewCount”:0,“喜欢”: 0, "tags" : [ ], "title" : "今天是个好日子", "__v" : 0
标签: node.js mongodb mongoose aggregation-framework