This is my MongoDB schema:
var partnerSchema = new mongoose.Schema({
name: String,
products: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Product'
}]
});
var productSchema = new mongoose.Schema({
name: String,
campaign: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Campaign'
}
]
});
var campaignSchema = new mongoose.Schema({
name: String,
});
module.exports = {
Partner: mongoose.model('Partner', partnerSchema),
Product: mongoose.model('Product', productSchema),
Campaign: mongoose.model('Campaign', campaignSchema)
}
And I wondering how can I remove object from any document taking into account references (maybe should I use somehow populate from mongoose)? For example if I will remove Product
then I assume that I will remove also ref ID in Partner
and all Campaigns
which belong to this Product
.
At the moment I removing in this way:
var campSchema = require('../model/camp-schema');
router.post('/removeProduct', function (req, res) {
campSchema.Product.findOneAndRemove({ _id: req.body.productId }, function (err, response) {
if (err) throw err;
res.json(response);
});
});
However in mongo still left references.
You would have to nest your calls to remove the product id from the other model. For instance, in your call to remove the product from the
Product
collection, you could also make another call to remove the ref from thePartner
model within the results callback. Removing the product by default will remove its refs to theCampaign
Model.The following code shows the intuition above:
To remove the associated campaigns then you may need an extra remove operation that takes in the associated campaign id fro a given product id. Consider the following dirty hack which may potentially award you a one-way ticket to callback hell if not careful with the callback nesting:
Although it works, the above potential pitfall can be avoided by using async/await or the
async
library. But firstly, to give you a better understanding of the using multiple callbacks with theasync
module, let's illustrate this with an example from Seven Things You Should Stop Doing with Node.js of multiple operations with callbacks to find a parent entity, then find child entities that belong to the parent:With async/await, your calls will be restructured structured as
With the async module, you can either use the series method to address the use of callbacks for nesting code of multiple methods which may result in Callback Hell:
Series:
Or the waterfall:
Now going back to your code, using the async waterfall method you could then restructure your code to