【问题标题】:Linking 2 collections using Mongoose使用 Mongoose 链接 2 个集合
【发布时间】:2021-05-21 21:50:50
【问题描述】:

我试图通过保存它们之间的引用将 2 个集合链接在一起,但我不知道如何推入数组。我有以下架构:

公司架构

const mongoose = require('mongoose')

const companySchema = mongoose.Schema({
  name: {
    type: String,
    required: true
  },
  projects: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Project'
  }]
})

module.exports = mongoose.model('company', companySchema, 'companies')

项目架构

const mongoose = require('mongoose')

const projectSchema = mongoose.Schema({
  name: {
    type: String,
    required: true
  },
  company: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Company'
  }
})

module.exports = mongoose.model('project', projectSchema, 'projects')

我的创建项目路由器如下所示

router.post('/create', async function(req, res) {
  try {
    let project = new Project({ name: req.body.name, company: req.body.company })
    await project.save()
    res.status(201).send({ project })
  } catch (error) {
    res.status(500).json({
      error: 'Server error while creating project'
    })
  }
})

它正确地创建了Project。但现在我还需要将新创建的Project 推入Company 模式的projects 数组中。非常感谢您的帮助。

【问题讨论】:

    标签: mongodb express mongoose schema


    【解决方案1】:

    听起来更像是您想要引用与公司相关的项目,而不是实际添加对这些项目的引用。为此,您需要将公司的 id 存储到您的新项目中,我希望这就是您的 req.body.company 字段所代表的内容。

    一旦每个新项目都包含有效的companyId,您可能需要检查与同一公司关联的项目列表。为此,您需要在公司文档中填充一个虚拟字段:

    companySchema.virtual('projects', {
      ref: 'Projects',
      localField: 'id',
      foreignField: 'companyId'
    })
    

    当然,这只有在你稍微改写你的模式时才会起作用:

    const companySchema = mongoose.Schema({
      name: {
        type: String,
        required: true
      }
    })
    
    const projectSchema = mongoose.Schema({
      name: {
        type: String,
        required: true
      },
      companyId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Company'
      }
    })
    

    最后,当您想要查看公司的项目时,您必须使用companyDocument.populate('projects').execPopulate() 填充项目字段。这样,companyDocument.projects 将包含您要查找的数组。

    【讨论】:

      猜你喜欢
      • 2020-05-27
      • 2018-09-15
      • 2015-10-23
      • 2022-12-03
      • 2021-05-11
      • 2019-09-17
      • 2016-01-29
      • 2021-09-08
      • 2018-08-21
      相关资源
      最近更新 更多