3

I'm working with some old data where some of the schema has a "mixed" type.

Basically sometimes a value will be a referenced ObjectID, but other times it'll be some text (super poor design).

I unable to correctly populate this data because of the times a non-ObjectID appears.

So, for my actual question: Is it possible to create a populate (on a collection) that is conditional; I need to be able to tell the populate to skip those other values.

joseym
  • 1,332
  • 4
  • 20
  • 34

1 Answers1

1

Yes, you can do that check the middleware function on the Mongoose API reference

http://mongoosejs.com/docs/middleware.html

What you need to do is before you populate those data, you validate the data if is is Object ID or not, if it is Object ID, you call next() to pass the next function, else you just return, this will skip it

Example

xSchema.pre('validate', function(next){
    var x = this;
    var checkXType = typeof x.id;

    if (checkXType === String) {
        return;
    } else {
        next();
    }       
});
Tim
  • 3,755
  • 3
  • 36
  • 57
  • I haven't confirmed this yet since, but that seems perfectly reasonable. When I have a moment to test this out I'll get back to this. I hadn't even considered middleware - only a solution within the populate method. – joseym Sep 11 '14 at 16:36