Monday, 13 March 2017

Saving nested objects in Mongoose not working yet passing validation

Im seeing something very very unusual with Mongoose. Im using v4.8.1.

I have a schema called Gate and it has a property called histGate. I want to save data in the format:

histGate:{ 
    '4': 
        { 
            gateName: 'G1'
        },
    '5': 
        { 
            gateName: 'G5'
        } 
    },
    ...
    ...

So histGate will have property '4', '5', '7' and the values will be objects.

My decalred Mongoose Schema is:

histGate: { 
    type: {
        "gateName": {type: String
    }
}

I can save a property to histGate once and when I check in Mongo I see:

'4': 
    { 
        gateName: 'G1',
    },

However, then I try to save another property:

    return Gate.findById(gateId)
    .then(function(gateDb){

        gateDb.histGate['5'] = gate;

        return gateDb.save()
        .then(function(gateDb){
            console.log('saved and gateDb is ', gateDb);
            return gateDb;
        })
        .catch(function(err){
            console.log('err is ', err);
            throw err;
        });
    })
    .catch(function(err){
        console.log('err is ', err);
        throw err;
    });

It tells me it has saved. gateDb has histGate with '4' and '5' properties. Yet when I look at the Mongo database, it doesnt, it only has the '4' property. And when I query, it only has the '4' property.

So Mongoose is telling me everything is fine and dandy and that it has saved, yet it actually has not. Whats going on? Is my schema wrong?



via Mark

No comments:

Post a Comment