const userSchema = new Schema(
{
_id: Schema.Types.ObjectId,
name: String,
posts: [{ type: Schema.Types.ObjectId, ref: "Post" }],
following: [{ type: Schema.Types.ObjectId, ref: "User" }]
}
};
我想提取 'following'
数组中所有用户的所有帖子,将它们放入一个数组中,对它们进行排序,然后显示前 20 个。我想知道这是不是可能在游标内或者如果我必须将它加载到内存中。
function createFeed(user) {
User.findOne({ name: user })
.populate({
path: "following",
populate: {
path: "posts"
}
})
//put all the posts into one array
.sort(...) //sort by time created
.limit(...) //only get the newest n posts
.exec((err, result) => {
if (err) console.log("error", err);
console.log("result", //sorted tweets array);
});
};
(我不想过滤我的“帖子”集合中的所有帖子来检查它们是否由用户创建,因为那样会更昂贵)
最佳答案
您可以在 mongoDB 中使用 distinct
查询
db.User.distinct('following',{})
关于javascript - Mongoose 从多个对象中提取嵌套数组到一个数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53813627/