Doubt Dbref Mongodb

Asked

Viewed 231 times

4

I have two collections in mongodb called businesses and users:

********** Coleção Empresas **********

    {
      "_id": ObjectId("54f38340448d3f436993edf6"),
      "cnpj": "12345678900000",
      "razao": "EMPRESA TESTE",
      "status": 0,
      "cidade": "ARACAJU",
      "uf": "SE",
      "usuarios": {
        "$ref": "user",
        "$id": ObjectId("5126bc054aed4daf9e2ab772")
      }
    }

********** Coleção Usuarios **********

{
    "_id" : ObjectId("5126bc054aed4daf9e2ab772"),
    "cnpj" : "12345678900000",
    "usuario" : "USER 01",
    "senha" : "1234",
    "chave" : "12345",
    "status" : 0,
    "codigo" : "120",
    "tipo" : "A"
}

I’m having a hard time getting one find with the company data information together with the user data searched.

I know there’s a reference in the documentation where something like this:

{ "$ref" : <value>, "$id" : <value>, "$db" : <value> }

Below follows a projection of how I would need the result:

********* RESULTADO **********

 {
   "_id": ObjectId("54f38340448d3f436993edf6"),
   "cnpj": "12345678900000",
   "razao": "EMPRESA TESTE",
   "status": 0,
   "cidade": "ARACAJU",
   "uf": "SE",
   "usuarios": {
     "_id": ObjectId("5126bc054aed4daf9e2ab772"),
     "cnpj": "12345678900000",
     "usuario": "USER 01",
     "senha": "1234",
     "chave": "12345",
     "status": 0,
     "codigo": "120",
     "tipo": "A"

   }
 }

Thank you in advance to everyone who can help.

  • If you are using Mongoose, you can use populate. http://mongoosejs.com/docs/populate.html

1 answer

1

Mongodb is not able to mount this structure natively. The "Join" has to be done manually by your application - this logic could be abstracted by a library. That is, basically what you can do is: find the company, extract the ref and the user id and perform a query to recover the user, and finally combine the results manually in a single document.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.