问题
Here is my schema:
/** Schemas */
var profile = Schema({
EmailAddress: String,
FirstName: String,
LastName: String,
BusinessName: String
});
var convSchema = Schema({
name: String,
users: [{
type: Schema.Types.ObjectId,
ref: 'Profiles'
}],
conversationType: {
type: String,
enum: ['single', 'group'],
default: 'single'
},
created: {
type: Date,
default: Date.now
},
lastUpdated: {
type: Date,
default: Date.now
}
});
/** Models */
db.Profiles = mongoose.model('Profiles', profile);
db.Conversations = mongoose.model('ChatConversations', convSchema);
module.exports = db;
Then I try to populate Users using following code (http://mongoosejs.com/docs/populate.html):
db.Conversations.find(query).populate('users').exec(function (err, records) {
console.log(records);
});
This is returning records
but users
array as a blank array []
.
I also tried the other way around (http://mongoosejs.com/docs/api.html#model_Model.populate):
db.Conversations.find(query, function (err, records) {
db.Conversations.populate(records, {path: "users", select: "BusinessName"}, function (err, records) {
console.log(records);
});
});
Results are same. When I checked references into profile collection records are there.
Any idea what wrong here?
回答1:
I got it working by renaming model (the 3rd arguement):
mongoose.model( "Profiles", profile, "Profiles" );
The issue was Mongoose was searching for profiles
collection but its there as Profiles
in database. So I renamed it to Profiles
to match the exact name.
Phewww! Thanks to me.
回答2:
I found that you have declared profile schema but ref profiles.
ref: 'Profiles'
var profile = Schema({
EmailAddress: String,
FirstName: String,
LastName: String,
BusinessName: String
});
来源:https://stackoverflow.com/questions/40012717/mongoose-populate-not-working-with-array-of-objectids