calling a rest function in another rest function

I have two resources, called "project" and "tag". When adding a new project, the data is transferred over the POST, and is passed into project.create(req, res). This saves the project in the mongodb database, and returns res.send(200); on success.

I'd like projects and tags to have a many-to-many relationship, so that I can easily list all tags, list project tags, and list tag projects.

The easiest way to store these tags would be to find+upsert these tags in the project.create function, and then save an array of their ids in an array project.tags. However, I feel like this is violating DRY... I have this same tag find+upsert code in tag.create(req, res).

How can I make it so that when project.create is called, to call tag.create? I also just realized, would this be better if I created some middleware that did the find+upsert?

Disclaimer: This answer deals with general good practices for REST APIs (not particularly with MongoDB).

One important thing to understand about real-life REST APIs, is that some resources can be read-only (typically generated with MapReduce from read-write resources).

Let's suppose you have conceptually an n-n association between projects and keywords. The more natural place to modify such links is in projects. So you'll have, for example:

  • GET, PUT or DELETE /project/stackOverflow (real object),
  • GET /keyword/QnA (virtual object aka query).