Using MongoDB,
I’ve got a model Enterprise
, with a comments
field :
...
comments: [{ type: mongoose.Schema.Types.ObjectId, ref: "Comment" }],
...
My Comment
model has this schema :
const mongoose = require("mongoose");
const schema = new mongoose.Schema(
{
author: String,
content: String,
enterpriseId: { type: mongoose.Schema.Types.ObjectId, ref: "Enterprise" },
employeeId: { type: mongoose.Schema.Types.ObjectId, ref: "Employee" },
},
{
timestamps: true,
}
);
module.exports = function (connection) {
return connection.model("Comment", schema);
};
Comment
model can be used by both Enterprise
and Employee
model.
When I create a comment from Enterprise
, the comment has the right enterpriseId
in the document. But, when I access to the Enterprise
comments on forest, I’ve go an error, because there is no comments
reference added to the comments array of Enterprise
model.
My question is : is there an easy way to reference the comment directly in the comments
array of Enterprise
model when creating the comment, without adding the reference through a hook (after comment creation, for instance) ?