sabari
sabari

Reputation: 2625

Mongoose populate issue - array object

My schema is as below

Sectionschema

var SectionSchema = new Schema({
    name: String,
 documents : {
        type : [{
            type: Schema.ObjectId,
            ref: 'Document'
        }]
    }
}

}

DocumentSchema

var DocumentSchema = new Schema({
    name: String,
    extension: String,
    access: String, //private,public
    folderName : String,
    bucketName : String,
    desc: String
});

Api.js

exports.section = function(req, res, next, id) {  

    var fieldSelection = {
        _id: 1,
        name: 1,       
        documents : 1
    };

    var populateArray = [];
    populateArray.push('documents');

    Section.findOne({
        _id: id
    }, fieldSelection)
        .populate(populateArray)
        .exec(function(err, section) {
            if (err) return next(err);
            if (!section) return next(new Error('Failed to load Section ' + id));
            // Found the section!! Set it in request context.
            req.section = section;
            next();
    });
}

If I go this way, I have the 'documents' object is []. However if I remove, "populateArray.push('documents');" then I get documents:['5adfsadf525sdfsdfsdfssdfsd'] -- some object Id (atleast)

Please let me know the way I need to populate.

Thanks.

Upvotes: 0

Views: 103

Answers (2)

Rohail Najam
Rohail Najam

Reputation: 1041

If you just want "documents" in your schema pointing to Array of ObjectID which you will populate later. then you can use this.

var SectionSchema = new Schema({
name: String,
documents : [{
        type: Schema.ObjectId,
        ref: 'Document'
    }]    
});

And use the following to populate it

 Section.findOne({
        _id: id
    }, fieldSelection)
        .populate('documents')
        .exec(function(err, section) {
            if (err) return next(err);
            if (!section) return next(new Error('Failed to load Section ' + id));
            // Found the section!! Set it in request context.
            req.section = section;
            next();
    });

Upvotes: 0

Jayram
Jayram

Reputation: 19588

Change your query to

Section.findOne({
        _id: id
    }, fieldSelection)
        .populate('documents.type')
        .exec(function(err, section) {
            if (err) return next(err);
            if (!section) return next(new Error('Failed to load Section ' + id));
            // Found the section!! Set it in request context.
            req.section = section;
            next();
    });

and this works. You need to give the path to populate.

Upvotes: 1

Related Questions