I have two schemas one being the category schema, and the other being the article schema. A user has to enter title, summary and add some categories. The categories are getting uploaded to the category schema but is not getting linked with articles. It showing empty array.
app.post("/upload", async (req,res) => {
const { title, summary, categoryIds } = req.body;
const categoryNamesArray = req.body.categories.split(',').map(category => category.trim());
try {
// Find or create categories based on user input
const categoryObjects = [];
for (const categoryName of categoryNamesArray) {
let category = await Category.findOne({ name: req.body.categories });
if (!category) {
category = new Category({ name: req.body.categories });
await category.save();
}
categoryObjects.push(category);
}
const newArticle = new article({
title: title,
summary: summary,
category: categoryObjects
});
// await newArticle.populate('categories');
await newArticle.save();
console.log('Article saved successfully:', newArticle);
res.status(200).send('Article saved successfully');
} catch (err) {
console.error(err);
res.status(500).send('Error saving article');
}
I tried to remove the category schema and, add categories inside the article schema, but it also returned an empty array
Your filter is wrong.
should be
And similarly correct it here as well