javascript - Mongoose 从多个对象中提取嵌套数组到一个数组中

标签 javascript node.js mongodb mongoose

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/

相关文章:

javascript - 无需单击即可展开所有切换

node.js - 语法错误 : Unexpected token U in JSON at position 0 at JSON. 在 angular8 中解析

ruby-on-rails - 将 Activerecord 数据库迁移到 Mongoid

mongodb - 在窗口 8 上安装 mongodb

javascript - 如何在javascript中生成连续颜色列表

javascript - 如何让应用程序在其内部返回搜索结果以实现离线快速页面导航?

javascript - jQuery -> 检查元素的可见性

node.js - nodejs, expressjs 服务于 PHP 文件

node.js - 使用node.js、express和socket.io的设计选择

performance - MongoDB高效处理嵌入式文档