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?
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.
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(..)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With