Mongoose relationships

3

How can I relate embedded collections? Example; suppose we have the collections A, B, C and that B is embedded in A, but in turn I want to relate B with C.

'use strict'
/*
   Module dependencies
*/
import mongoose from 'mongoose'

const Schema = mongoose.Schema

export default () => {

  let B = new Schema({
    ...
  })

  let A = new Schema({
    B: [B] // embed schema
  }, { collection: 'A' })

  return mongoose.model('A', A)
}

Now in another file is what I call C :

'use strict'
/*
  Module dependencies
*/
import mongoose from 'mongoose'

const Schema = mongoose.Schema

export default () => {
  let C = new Schema({
    B: {
      type: Schema.ObjectId,
      ref: 'B'
    }
  })
  return mongoose.model('C', C)
}
    
asked by Juan David Echeverry Rivera 12.09.2016 в 17:20
source

2 answers

2

You need to create the reference using a Schema.ObjectId object that is the type of data used for the identifier of a document in MongoDB. The ref property indicates where search for that identifier.

In this example, we created a EsquemaA scheme to create the A model that has a reference to the B model.

var EsquemaA = Schema({
  refB: {
    type: Schema.ObjectId,
    ref: 'B'
  }
});

var EsquemaB = Schema({
  refC: {
    type: Schema.ObjectId,
    ref: 'C'
  }
});

var EsquemaC = Schema({
  // ...
});

mongoose.model('A', EsquemaA);
mongoose.model('B', EsquemaB);
mongoose.model('C', EsquemaC);

In this example, the RefB field is a reference to the model identifier B .

Now, to reference it, you must use the object that represents the referenced document. In this example, we have the object b that is a document type B :

let b = new B();
b.save();

Now, we create the document a that is of type A and we make the reference to the document b in the property or field refB :

let a = new A();
a.refB = b;
a.save();

Since it is only a reference to ObjectID of an actual document, Mongoose has to fill the instance of A with the instance of B. To do this you must tell Mongoose to fill in the A object using the% method % co when you retrieve the document.

That already depends on you and it's not what you're asking, but one way is to use the populate() method to populate the property find() , for example:

A
  .find()
  .populate('refB')
  .exec(function(err, a) {
  ...
});
    
answered by 12.09.2016 / 17:54
source
1

I found a way to do it, thank you very much everyone. I leave the link of the solution here: link

    
answered by 13.09.2016 в 02:58