Linking 2 collections using Mongoose

I'm trying to link 2 collections together by saving a reference between them, but I'm stuck on how to push into the array. I have the following schemas:

Company schema

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')

Project schema

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')

My create Project router looks like this

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'
    })
  }
})

It's correctly creating the Project. But now I need it to also push the newly created Project into the projects array of the Company schema. Would really appreciate the help.



Read more here: https://stackoverflow.com/questions/66268518/linking-2-collections-using-mongoose

Content Attribution

This content was originally published by user2534723 at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: