I've been searching extensively for a way to reference documents bidirectionally in Mongoose. Despite all the documentation and examples provided in Populate, they only show how to save the objectID of one document in another. Let's say I have a parent document ("category") and multiple child documents ("subcategories"), and I want to reference the parent within the children and vice versa. How can this be achieved?
The only solution that crossed my mind was to add objectID references before saving the documents to the database. Here is the code snippet for that:
Category Schema:
let mongoose = require("mongoose")
let categorySchema = new mongoose.Schema({
name: String,
sale_type: String,
sub_categories: [{type: mongoose.Schema.Types.ObjectId, ref:
"SubCategory" }]
})
module.exports = mongoose.model("Category", categorySchema)
Subcategory Schema:
let mongoose = require("mongoose")
let subcategorySchema = new mongoose.Schema({
name: String,
sale_type: String,
category: {type: mongoose.Schema.Types.ObjectId, ref: "Category" }
})
module.exports = mongoose.model("SubCategory", subcategorySchema)
Main file: (This route is intended for creating new "Categories")
app.post("/categories", function(req, res){
let name = req.body.name
let sale_type = req.body.sale_type
let sub_categories = req.body.sub_categories.split(",")
let category = new Category({
_id: new mongoose.Types.ObjectId(),
name: name,
sale_type: sale_type,
sub_categories: []
})
sub_categories.forEach(function(element){
let sub_category = new SubCategory({
_id: new mongoose.Types.ObjectId(),
name: element,
sale_type: sale_type,
category: category._id
})
sub_category.save(function(err, subcat){
if (err){
console.log(err);
res.status(500).send("")
} else {
category.sub_categories.push(subcat._id)
}
})
})
category.save(function(err, cat){
if (err){
console.log(err)
res.status(500).send("")
} else {
res.status(200).json(cat)
}
})
})
Upon hitting the "/categories" route to create a new category, the server response meets my expectations:
{
"sub_categories": [
"5c2340bf4641017050567fe8",
"5c2340bf4641017050567fea"
],
"_id": "5c2340bf4641017050567fe6",
"name": "cat",
"sale_type": "retail",
"__v": 0
}
However, when checking with mongo shell for categories saved in the database, this is what is actually stored:
{ "_id" : ObjectId("5c2340bf4641017050567fe6"), "sub_categories" : [ ],
"name" : "cat", "sale_type" : "retail", "__v" : 0 }
and the sub_categories array remains empty!!!