ASchema = new mongoose.Schema({ | |
name: String, | |
B: [BSchema] | |
}); | |
var BSchema = new Schema({ | |
name: String | |
}); | |
var CSchema = new Schema({ | |
name: String, | |
B: { | |
type: Schema.ObjectId, | |
ref: 'BSchema' | |
} | |
}); | |
//This is OK, but not one time mongoose search: | |
CSchema.find({ | |
name: 'C_xxx' | |
}).exec(function(err, docC) { | |
docC.forEach(function(o) { | |
var BId = o.B; | |
ASchema.findOne({ | |
'B._id': BId | |
}, { | |
'B.$': 1 | |
} | |
).exec(function(err, docA) { | |
var Bname = docA.B[0].name; | |
var Cname = docA.name; | |
}); | |
}); | |
}); | |
//wrong in populate: | |
CSchema.find({ | |
name: 'C_xxx' | |
}) | |
.populate('ASchema.B') | |
.exec(function(err, docC) { | |
docC.forEach(function(o) { | |
var Bname = o.B.name; | |
//ERROR:o.B is a objectId,o.B.name is undefined | |
//Aname can't find | |
}); | |
}); | |
/* | |
Data like this: | |
ASchema = { | |
name: "A_xxx", | |
B: [{ | |
_id: 1, | |
name: "B_xxx" | |
}, { | |
_id: 2, | |
name: "B_xxx" | |
}] | |
} | |
CSchema = [{ | |
name: "C_xxx", | |
B: 1 | |
}, { | |
name: "C_xxx", | |
B: 2 | |
}] | |
*/ |
![]() |
1
shuson 2014-06-13 16:42:57 +08:00
when populate fields, it only works if there is ref to children from the parent schema
|