Reputation: 1022
Mongoose isnt playing very well with population. this is my model
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
mongoose.connect(process.env.MONGO_URI);
var userSchema = new Schema({
username: String,
password: String,
books: [{type: Schema.Types.ObjectId, ref: 'User'}]
}
);
var bookSchema = new Schema({
bookid: {type:String, unique:true, required:true},
imgURL: String
});
module.exports.user = mongoose.model('User', userSchema);
module.exports.book = mongoose.model('Book', bookSchema);
The database looks correct.
{ "_id" : ObjectId("56a17cd70a498fcc37cdbe60"), "username" : "test", "password" : "test", "books" : [ ObjectId("56a17d21d43dc32a3a9837de"), ObjectId("56a17ee5d43dc32a3a9837e4"), ObjectId("56a17f5dd43dc32a3a9837e6"), ObjectId("56a17f9fd43dc32a3a9837e8") ], "__v" : 4 }
But when I do a populate I get an empty 'books' array
users.findOne({'_id':userid}).populate('books').exec(function(err,data){
if (err) return console.error(err);
if(data){
}
});
Everything is there it simply will not populate. Any suggestions would be greatly appreciated.
Upvotes: 2
Views: 2713
Reputation: 48526
It seems the incorrect ref
in the userSchema
, it should reference to book
schema rather than user
schema itself.
var book = mongoose.model('Book', bookSchema);
...
books: [{type: Schema.Types.ObjectId, ref: 'book'}]
Upvotes: 5