Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to populate a self reference in a mongoosejs schema?

I have a mongoose model schema which I am attempting to build for some preexisting mongodb documents. The existing mongo documents have a self reference to the same collection. I have tried to create a schema which represents this relationship and then have attempted to make use of the populate method. The schema looks like the below (some properties removed for brevity):

var fileSchema = new Schema({
    _id: { type: String },
    pcap: {
        files: [{ type: Schema.Types.ObjectId, ref: 'Files' }]
    }
});

var file = artifactConn.model('Files', fileSchema, 'info');

I then use the above model to query and then populate like this:

models.file.findById("91320684-9a1a-4f2a-a03f-63a7a208ec9b")
.populate('pcap.files') // have also tried just 'files' w/ the same result
.exec(function (err, file) {
    if (!err) {
        console.log(file);
    } else {
        console.log(err);
    }
});

which results in this

{ _id: '91320684-9a1a-4f2a-a03f-63a7a208ec9b',
  pcap: 
   { files: [] }
}

If I check my document in mongohub it looks like this

{ "_id" : "91320684-9a1a-4f2a-a03f-63a7a208ec9b",
  "pcap" : {
    "files" : [ 
      { "_id" : "e4eed129-b4aa-46fc-8df2-3f3f92e6fe53" }, 
      { "_id" : "8c0ecb98-452e-475d-a521-feba5c3d1426" }, 
      { "_id" : "4b87c467-f396-4bcf-a7b0-8419e8441ec0" } ] } }

Am I doing something wrong with my call to populate? Is it the way that I have my schema setup? Is it the way the data is being stored?

like image 828
ahsteele Avatar asked Apr 16 '13 04:04

ahsteele


2 Answers

Your schema is incorrect. The schema you have would match a collection like this:

{ "_id" : "91320684-9a1a-4f2a-a03f-63a7a208ec9b",
  "pcap" : {
    "files" : [ 
      { ObjectId("e4eed129-b4aa-46fc-8df2-3f3f92e6fe53") }, 
      { ObjectId("8c0ecb98-452e-475d-a521-feba5c3d1426") }, 
      { ObjectId("4b87c467-f396-4bcf-a7b0-8419e8441ec0") } ] } }

The schema should be:

var fileSchema = new Schema({
    _id: { type: String },
    pcap: {
        files: [{ 
            _id: { type: String, ref: 'Files' }
        }]
    } });

That should work.

like image 146
matthewtole Avatar answered Oct 13 '22 21:10

matthewtole


Schema looks ok. Store the data the same way and you should be good: e.g.

{ "_id" : "91320684-9a1a-4f2a-a03f63a7a208ec9b",
  "pcap" : {
  "files" : [ ObjectId("e4eed129-b4aa-46fc-8df2-3f3f92e6fe53"), ObjectId("8c0ecb98-452e-475d-a521-feba5c3d1426"), ObjectId("4b87c467-f396-4bcf-a7b0-8419e8441ec0")] 
  } 
}

Then

Model.find(..).populate('pcap.files').exec(..)
like image 40
aaronheckmann Avatar answered Oct 13 '22 21:10

aaronheckmann