D
D
Devero972020-12-28 22:38:53
MongoDB
Devero97, 2020-12-28 22:38:53

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: 'Ошибочка'})
  }
}

In the model they are connected like this:
tags: [
    {
      type: Schema.Types.ObjectId,
      ref: 'tags'
    }
  ]
  categories: [
    {
      ref: 'categories',
      type: Schema.Types.ObjectId
    }
  ]

How can I change another collection when updating data? Here I have 2 options selected from the list, but how can I do this to overwrite it? If I make one selection from the loaded list, then everything will be saved as it should, but the previously selected item will also be present in the other collection

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question