Mongoose Populate not working with Array of ObjectIds
Asked Answered
L

1

2

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?

Lodgment answered 13/10, 2016 at 5:8 Comment(2)
all seems right. and its working for me. cant see anything wrongHydropic
which one worked?Lodgment
L
5

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.

Lodgment answered 13/10, 2016 at 6:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.