Alex Shest
Alex Shest

Reputation: 172

NodeJS + Mongoose: population doesnt work

I want to add to Blog object several Categories objects, and after this get access to the first category of a Blog.

var ObjectId = mongoose.Schema.Types.ObjectId;

var categorySchema = mongoose.Schema({
    title: String,
    blogs: [{ type: ObjectId, ref: 'Blog' }]
})

var blogSchema = mongoose.Schema({
    title: String,
    description: String,
    category: [{ type: ObjectId, ref: 'Category' }],
    created: {type: Number, default: new Date().getTime()}
})

var Category = mongoose.model('Category', categorySchema)
var Blog = mongoose.model('Blog', blogSchema)

exports.addBlog = function (object, callback) {
    Blog({
        title: object.title,
        description: object.description,
        category: object.category //array of sting ObjectID's - ['',''] – from multiselect box
    }).save(function (err, _) {
            Blog
                .find({title: _.title})
                .populate('category')
                .exec(function (err, __) {
                    if (err) return handleError(err);
                    console.log('Category is ', __.category[0].title);
                })
            callback(err, _);
        });
}

As a result I get:

TypeError: Cannot read property '0' of undefined

It seems Mongoose couldn't find object in last callback (__), but I've checked – _.title is valid. How to populate it? Thanks.

Upvotes: 2

Views: 319

Answers (1)

Alex Shest
Alex Shest

Reputation: 172

The problem was Blog.find() returns an array, I should use __[0].category[0].title or find with findOne().

Upvotes: 1

Related Questions