Mongoose Populate not working with Array of ObjectIds

狂风中的少年 提交于 2019-12-11 03:02:34

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!