简体   繁体   中英

Update field inside object in mongodb

I'm trying to update a object inside another but when the object is updated replace all information.

Structure

var userSchema = mongoose.Schema({

    local            : {
        email        : {type: String, unique: true},
        password     : String
    }
    name: String
});

before be updated

user

{
    name = 'foo',
    local {
        email: "foo@foo.com",
        password: "foopass"
    }
}

after be updated

{
    name = 'foo',
    local {
        email: "foo@foo.com"
    }
}

this is my query:

router.put('/:id', function(req, res) {

    User.findByIdAndUpdate(req.params.id, {
    $set: { name: req.body.name, local: {email: req.body.email} }
    }, { upsert: true },
    function(err, obj) {
        return res.json(true);
    });
});

Use dot notation in the $set key to target just the email property of local instead of updating the whole local object:

router.put('/:id', function(req, res) {

    User.findByIdAndUpdate(req.params.id, {
        $set: { name: req.body.name, 'local.email': req.body.email }
    }, { upsert: true },
    function(err, obj) {
        return res.json(true);
    });
});

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