我创建了2个模型,即用户、文章.它们的数据 struct 如下;

const userSchema = Schema({
  name: String,
  email: String,
  password: String
});
const User = mongoose.model(‘user’, userSchema);
module.exports = User;

——

const articleSchema = Schema({
  liked: Array,  // liked contains users’ _id who like this article
  content: String
})
const Article = mongoose.model(‘article’, articleSchema);
module.exports = Article

——

我想得到的所有文章的页面大小为10,每篇文章填充了一些用户的信息谁喜欢这篇文章.

例如,假设用户表和文章表的数据如下:

users = [
 { 
    _id: 1,
    name: ‘a’,
    email: ‘a.com’,
    password: ‘a’
 },
 { 
    _id: 2,
    name: ‘b’,
    email: ‘b.com’,
    password: ‘b’
 }
]

articles = [
  {
    _id: 1,
    liked: [1,2],
    content: “a&b”
  },
  {
     _id: 2,
     liked: [1],
     content: “a”
  }
]

预期的结果是:

  articles = [
   {
      _id: 1,
      liked: [
      { 
         _id: 1,
         name: ‘a’,
         email: ‘a.com’,
         password: ‘a’
       },
       { 
         _id: 2,
         name: ‘b’,
         email: ‘b.com’,
         password: ‘b’
       }
     ],
     content: “a&b”
   },
   {
       _id: 2,
       liked: [
       { 
          _id: 1,
          name: ‘a’,
          email: ‘a.com’,
          password: ‘a’
        }
       ],
        content: “a”
    }
]

我试着用Model.find(query)Model.aggregate(pipeline)来解决这个问题,但这两种方法各有优缺点,都达不到好的结果.请给我一个建议.

推荐答案

根据您所共享的内容,在Model.aggregate()查询中输入一个简单的$lookup将得到以下输出:

const articles = await Article.aggregate([
  {
    "$lookup": {
      "from": "users",
      "localField": "liked",
      "foreignField": "_id",
      "as": "liked"
    }
  }
]);

HERE章一个工作的例子

但是,如果要将模式更改为使用引用的文档,则可以在查询检索时使用populateArticle.liked数组中的每个_id替换为相应的User文档.无论哪种方式都会奏效.

这就是你如何使用populate:

const articleSchema = Schema({
  liked: [{ 
      type: mongoose.Schema.Types.ObjectId, 
      ref: 'User' // create a reference to User
   }],  
  content: String
})

那就go 做吧

const articles = await Article.find().populate({path: 'liked', model: User});

Note:这个包含populate()的示例使用的谓词是,每个User文档的每个User._id字段都是Mongoose ObjectId类型.

Node.js相关问答推荐

NX无法使用缓存运行根级脚本

为什么在导出的函数中调用node-sqlite3中的数据库方法时不起作用?

mongoose 模型填充问题

无法使用 Express 设置会话 cookie 的过期日期

Promise 和 Azure 语音转文本

DynamoDB 分页数据检索

在 getServerSideProps 中使用 EmailProvider 获取 NextAuth 会话会抛出 fs找不到模块

如何配置 Nginx React 和 Express

每个数组值在 mongodb 中查找一个文档

Typescript typeRoots 未检测到类型定义

获取数组的至少一个元素包含子字符串的文档

即使部署成功,也不会触发 Firebase 函数来填充 Firestore 集合.为什么?

fs.writefile 选项参数的可能值,尤其是只读文件的整数

如何限制 cron 表单将消息推送到 RabbitMQ?

`npm install` 以Killed结尾

您如何写入 aws lambda 实例的文件系统?

mongoose 模式中的嵌套对象

为什么模块级返回语句在 Node.js 中起作用?

如何忽略文件 grunt uglify

使用 gzip/deflate 压缩的简单 HTTP 请求