Skip to content

Model.populate() results in array, even if single ObjectID is being populated when using 'skipInvalidIds' option #8157

Description

@Hyperblaster

When calling Model.populate() on a document or an array of documents, Mongoose returns the populated path as an Array.

The expected behaviour would be that if the path's value is a single ObjectId, String or Object (using the skipInvalidIds property) it should return a single Document, and if the value is an array then to return an Array of documents.

Schema

var PhotoSchema = new Schema({
    title: {
        type: String,
    },
    data: {
        type: Schema.Types.Mixed,
    },
});

var Photo = mongoose.model('photo', PhotoSchema);

Example Document

{
  "title":"Example",
  "data":{
     "photographer":{
           "_id":"5a9390c84028396d2a374432",
           "title":"John Smith",
     }
  }
}

Code to Populate

var items; //Array of documents containing the example document above

return Photo.populate(items, {
          path:"data.photograpger",
          select: controller.basicFields,
          skipInvalidIds: true, 
}, done);                        

Current Output

{
  "title":"Example",
  "data":{
     "photographer":[
     {
           "_id":"5a9390c84028396d2a374432",
           "title":"John Smith",
     }
     ]
  }
}       

Expected Output

{
  "title":"Example",
  "data":{
     "photographer":{
           "_id":"5a9390c84028396d2a374432",
           "title":"John Smith",
     }
  }
}       

This is really in relation to the skipInvalidIds feature, as if the objects are depopulated when saved to the database everything works as expected, It's just for when there are objects in the database that aren't plain ObjectIds but are objects with an _id that cause the issue.

My understanding was that when using the 'skipInvalidIds' feature the data would stay the same as it originally was before calling populate(), It's seems like it's a bit smarter than that and is actually populating the object picking up the _id property. Which is nice, it just needs to understand whether it's a single ID or an array of multiple IDs when it returns

Metadata

Metadata

Assignees

No one assigned

    Labels

    confirmed-bugWe've confirmed this is a bug in Mongoose and will fix it.

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions