4

Our stack currently uses mongoose as a ODBM and I was wondering how exactly I should implement a RESTFUL request to determine whether a foregin key gets populated(i.e the forgeign key _id property gets replaced with the either the entire document or part of the document from another collection).

I know I could send up something like

?populate=CollectionName&populateFields=fieldsnames`

via a query string but something about that seems hacky to me and I was wondering what's considered the standard/best practice in this situation

Austin Davis
  • 3,516
  • 10
  • 27
  • 47

2 Answers2

0

MongoDb doesn't have joins. If the associated data is small enough, then it's suggested to embed the document. If you take that appoarch, then you could perform this simple query to check if the embedded document field is a document.

0 < db.products.count({_id : 3, rebateProgram : { $type : 3} })

In mongoose, I think it's

0 < productModel.find({}).where({_id : 3, rebateProgram : { $type : 3} }).count()

rebateProgram : {$type : 3} means only match the rebateProgram field if it's an with an embedded document. 3 is the BSON type for embedded document.

RESTful URL

A restful url to check the a property on a document could look like this.

The request would be a GET because you're retrieving a value and not modifying anything data.

GET: /??/:collectionName/:documentId/action

Example:

Request:

GET: /api/products/3/status?hasObject=rebateProgram

Response:

{
    id: 3,
    hasObject : { rebateProgram : true },
    success : true,
    errMsg : ""
}

However if it's always going to be the same field you're checking for, then include the status of the embedded field in the response. Like this. Example:

Request:

GET: /api/products/3/status

Response:

{
    id: 3,
    hasValidRebateProgram : true,
    success : true,
    errMsg : ""
}

More info:

Larry Battle
  • 9,008
  • 4
  • 41
  • 55
0

Allowing query parameters that lets the client add or remove fields returned by a resource's endpoint is not hacky in my opinion. I recommend reading this article on RESTful best practices. So your URL would look something like this:

Assuming you're talking about a GET route

GET /users/:user_id?fields=field1,some_other_field

You shouldn't need to represent your database in a RESTful URL. Think from a client's perspective. What would make sense to you if you didn't design the database? I think an API should expose behavior, not a database.

arjabbar
  • 6,044
  • 4
  • 30
  • 46