D
D
Devero972021-01-18 12:58:08
MongoDB
Devero97, 2021-01-18 12:58:08

How to update data between two collections?

Prompt, how it is possible to update the second collection, at update of the first? I create a tag, where I get a trace. data:

const Tag = require("../models/tag.model");
const Category = require("../models/category.model");
const slugify = require("slugify");

module.exports.create = async (req, res) => {
  try {
    const tag = new Tag({
      slug: slugify(req.body.title),
      category: req.body.category,
      categories: req.body.categories,
      name: req.body.name,
      premium: req.body.premium,
      title: req.body.title,
      description: req.body.description
    });

    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: "Произошла ошибка" });
  }
};


Schemes of two collections:
const { Schema, model } = require("mongoose");

const tagSchema = new Schema({
  title: {
    type: String,
    required: true
  },
  category: {
    type: String,
    required: true
  },
  slug: {
    type: String,
    required: true
  },
  name: {
    type: String,
    required: true
  },
  description: {
    type: String,
    required: true
  },
  premium: {
    type: Boolean
  },
  categories: [
    {
      ref: "categories",
      type: Schema.Types.ObjectId
    }
  ]
});

module.exports = model("tags", tagSchema);


const { Schema, model } = require("mongoose");

const categorieSchema = new Schema({
  name: {
    type: String,
    required: true
  },
  tags: [
    {
      type: Schema.Types.ObjectId,
      ref: "tags",
      default: []
    }
  ]
});

module.exports = model("categories", categorieSchema);


When creating, I found the second collection (categories) and added the tag ID to the array. But when I update, I can't delete or add the id of this tag to the categories. How can this be done?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander N++, 2017-05-17
@sanchezzzhak

device-detector

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question