简体   繁体   中英

How do I update an embedded document with a nested hierarchy?

I have an embedded document that needs to be updated. I have managed to get everything working except for one scenario: I am unable to get an embedded document with a nested hierarchy to get updated. Here is an example of what I'm attempting to do:

console.log('Phone type: ' + req.body.phone.type); // prints, e.g., 'Phone type: Work'
console.log('Phone #: ' + req.body.phone.number); // prints, e.g., 'Phone #: 555-555-5555'

var updateData = {
        "user.$.contact_info": {
            email: req.body.email,
            phone: {
                type: req.body.phone.type,
                number: req.body.phone.number
            }
        }
    };
    Group.update(
        { "user._id" : req.params.user_id },
        { $push : updateData },
        function(err,data) {
            console.log('Success!'); // I see the "Success!" message every time I save a record
        }
    );

Schema:

var contactInfoSchema = mongoose.Schema({
    created : {
        type: Date,
        default: Date.now
    },
    email : String
    phone: {
        type: String,
        number: String
    }
});

var userSchema = mongoose.Schema({
    created : {
        type: Date,
        default: Date.now
    },
    contact_info : [contactInfoSchema]
});

var GroupSchema = mongoose.Schema({
    created : {
        type: Date,
        default: Date.now
    },
    users : [userSchema]
});

What I find is that I can create records, but only the email address is stored, not the phone information. When inspecting the console I can see that the phone type and phone number info is being sent, but it just isn't updating in the database. What am I doing wrong?

The problem in in the "contactInfoSchema" with the use of the "type" keyword. You need this:

var contactInfoSchema = mongoose.Schema({
    created : {
        type: Date,
        default: Date.now
    },
    email : String
    phone: {
        "type": { "type": String },
        number: String
    }
});

So basically mongoose is confused since you tried to call a "sub-document" field "type", and it thinks that is the data "type" for the field "phone". Declared as above all works fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM