Answer the question
In order to leave comments, you need to log in
How to update one collection when changes occur in another?
I have 2 related collections. When filling in the data in the form, I select the list loaded in advance, where I select the necessary IDs, when filling out the table, I send the data to the server and process it like this:
const Category = require('../models/category.model')
const Tag = require('../models/tag.model')
const slugify = require('slugify')
module.exports.createTag = async (req, res) => {
try {
const tag = new Tag({
premium: req.body.premium,
categories: req.body.categories,
title: req.body.title,
tag: slugify(req.body.title),
description: req.body.description,
name: req.body.name
})
await tag.save()
req.body.categories.forEach(async item => {
const category = await Category.findById(item._id)
category.tags.push(tag._id)
await category.save()
})
res.status(201).json({message: 'Тег успешно создан'})
} catch (e) {
res.status(500).json({message: 'Ошибочка'})
}
}
tags: [
{
type: Schema.Types.ObjectId,
ref: 'tags'
}
]
categories: [
{
ref: 'categories',
type: Schema.Types.ObjectId
}
]
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question