How to easily add reference to model

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) ?

Hello @XavierColombel,

Sorry for the delay, your post had an issue and went under our radars.

I see 2 solutions in your case:

  1. As you mentioned, create the relationship using hooks. The advantage will be that this specific rule will also be enforced when your application creates comments (if it uses the same code)
  2. Override default routes for creation on your agent. This will depend on the agent’s version you are using.

Can you please share with us the name of your project, along with the agent type and version as it is requested in the topic template?

Thank you.