Answer the question
In order to leave comments, you need to log in
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: "Произошла ошибка" });
}
};
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);
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