Using Mongoose
and a RESTful API
I'd like to have 2 collections (organizations
and projects
), whereas the Schema
of the former should hold a field projects
of type [ObjectId]
, which references documents of the latter - and vice versa.
Creating a new organization (POST /organizations) one could either (a) leave the projects
field blank and add project documents later (POST /projects) or (b) create some projects with it already.
The problems for (b):
It seems to be in conflict with RESTfulness, because posting a new organization should have a different API point than posting a new project - but we want to achieve both in one go.
When we create a new organization the field
projects
should hold an array of ObjectIds referring to the corresponding projects - but these won't have IDs yet.
There are probably many ways to accomplish the goal - i.e. 2 successive POST requests: Projects first, then the organization. But I'd like to learn about best-practice for this szenario.
Oranization Schema:
{
name: { type: String, required: true },
address: { type: String },
// projects = array of ObjectIds referring to Project documents
projects: { type: [Mongoose.Schema.Types.ObjectId] }
}
Project Schema:
{
name: { type: String, required: true },
start: { type: Date },
end: { type: Date },
organization: { type: Mongoose.Schema.Types.ObjectId }
}
Provided problem description and code are simplified examples for a bigger project that will have many models/collections with a lot of cross-referencing.
One could have projects as an array of sub-documents of an organization document, but I'd prefer to have the projects as an independent collection, since it should be possible to request the whole collection for a projects view, without having to crawl through the organizations documents.