Fork me on GitHub

mongoose 过滤外联子文档

案例:用户下有多个角色,用户和角色是两个文档,查询用户时显示其拥有的角色并过滤禁用的角色

const mongoose = require('mongoose')
const fs = require('fs')

mongoose.connect('mongodb://localhost/test', { useUnifiedTopology: true, useNewUrlParser: true })
const User = mongoose.model('User', new mongoose.Schema({
  name: String,
  roles: [{ type: mongoose.Types.ObjectId, ref: 'Role' }]
}), 'test_user');

const Role = mongoose.model('Role', new mongoose.Schema({
  name: String,
  disable: Boolean
}), 'test_role');

(async function () {
  await User.deleteMany({})
  await Role.deleteMany({})
  const user = await new User({ name: '嘎嘎' }).save()
  const role01 = await new Role({ name: '管理员', disable: false }).save()
  const role02 = await new Role({ name: '销售员', disable: false }).save()
  const role03 = await new Role({ name: '狗管理', disable: true }).save()
  user.roles.push(...[role01, role02, role03])
  await user.save()
  const res2 = await User.find().populate({
    path: 'roles',
    match: { disable: false }
  })
  fs.writeFileSync('./res.json', JSON.stringify(res2))
  mongoose.disconnect()
}()).catch(err => {
  console.error(err)
  mongoose.disconnect()
})

输出(过滤掉了disable=true的角色):

[
  {
    "roles": [
      {
        "_id": "5dcdffd60fa82a1304cce09a",
        "name": "管理员",
        "disable": false,
        "__v": 0
      },
      {
        "_id": "5dcdffd60fa82a1304cce09b",
        "name": "销售员",
        "disable": false,
        "__v": 0
      }
    ],
    "_id": "5dcdffd60fa82a1304cce099",
    "name": "嘎嘎",
    "__v": 1
  }
]