Conditional set in mongo findOneAndUpdate

I have a "family" scheme in which "parents" are built in, for example ...

var parentSchema = new mongoose.Schema({
    firstName: String,
    // ...other simple fields
    someId: mongoose.Schema.Types.ObjectId,
    someOtherId: mongoose.Schema.Types.ObjectId,
});

var familySchema = new mongoose.Schema({
    // ...other fields
    parents: [parentSchema]
});

Until recently, I only had a field someIdrelated to another document, and I had this code to set it ...

familySchema.statics.setSomeId = function(someId) {
    return this.findOneAndUpdate(
        { /* some query that finds a parent */ },
        { $set : { "parents.$.someId" : someId } });
};

Now I find that I sometimes need to maintain two connections. If someIdalready installed, I would like to initialize someOtherId. Here is my last attempt ...

familySchema.statics.setSomeId = function(someId) {
    return this.findOneAndUpdate(
        { /* some query that finds a parent */ },
        {$cond: { 
            if: { $eq: { someId: null } }, 
            then: { $set : { "parents.$.someId" : someId } },
            else: { $set : { "parents.$.someOtherId" : someId } }
        }});
};

But I'm pretty confused by the syntax. In particular, this is the part that checks for NULL. I tried several combo $ if and $ eq, but I can not get it right. Can you help me figure out how to set the second identifier if the first is already set?

0
source share

Source: https://habr.com/ru/post/1589317/


All Articles