Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose.js conditional populate

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.

like image 372
joseym Avatar asked May 08 '26 09:05

joseym


1 Answers

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();
    }       
});
like image 199
Tim Avatar answered May 11 '26 00:05

Tim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!