search

Home  >  Q&A  >  body text

node.js - How mongoose filters and paging based on related tables

Problem Background

  1. The following two schemas

    Columns: {
        active: Boolean,
        name: String
    }
    
    News: {
        column: {type: Schema.Types.ObjectId, ref: 'columns'},
        title: String,
        content: String
    }
  2. column Medium active has the requirement to be modified by the configuration, and the news table has a large number of insertion requirements

Problem Description

  1. How to perform paging query on news, and the query condition is column.active is true?

  2. How to count the query conditions?

Solution attempt

1.

   News.find().populate({
       path: 'column',
       match: { active: true }
   }).limit(10).skip(0).exec(function(err, news) {
       if (err) {
           console.log(err);
       } else {
           console.log(news);
       }
   });
输出结果:
news:[
  {
    "title": "这篇资讯的所属栏目正在开放",
    "column": {
      "active": true,
      "createdAt": "2017-04-11T10:35:29.747Z",
      "id": "58ecc960a4db1e3fc01c2d6d"
    },
    "updatedAt": "2016-11-29T08:55:42.000Z",
    "id": "5923ab21415f8f3bc43f8515"
  },
  {
    "title": "这篇资讯的所属栏目已被屏蔽",
    "column": null,
    "updatedAt": "2016-11-29T08:47:18.000Z",
    "id": "5923ab21415f8f3bc43f83bd"
  }
]
期望获取的结果是只有column中active为true的数据
尝试失败
PHPzPHPz2766 days ago1826

reply all(1)I'll reply

  • 滿天的星座

    滿天的星座2017-05-24 11:37:40

    1. In the situation you mentioned, populate is like this, so most of the time populate is very useful when making an association with a document, but when making an association with multiple documents that meet the conditions, this is the situation you encountered. , if there is no association, null will be returned.

    2. It is recommended that you make the following modifications to the data model:

    1) The data model method you use is the reference method, which is a traditional paradigm modeling method. It is more difficult to use in MongoDB;

    2) Consider using anti-paradigm modeling. The name sounds very advanced, it just uses sub-document to achieve association. In your requirement, it is easier to embed columns into news as subdocuments.

    For reference.

    Love MongoDB! Have fun!

    reply
    0
  • Cancelreply