mongoose更新嵌套值

我有像我这样的mogoose模式的嵌套属性:

const userSchemaValues = { username: { type: String, required: [true, 'Username required'], trim: true, unique: true, lowercase: true }, password: { type: String, required: [true, 'Password required'], trim: true, minlength: 8 }, ... prop: { prop_1: String, prop_2: String } }; 

 valuesToUpdate.prop = _.pick(req.body, 'prop_1', 'prop_2'); log.debug(JSON.stringify(valuesToUpdate)); User.update({_id: req.params.id}, {$set: valuesToUpdate}) .then((data) => { return res.json({message: data}); }) .catch(err => { log.error(err); return next({message: 'Error updating User.'}); }); 

但是,当我用一个像这样的对象( {"prop":{"prop_1": "somevalue"}设置prop_1和_2的用户上执行User.update({_id: req.params.id}, {$set: valuesToUpdate}) {"prop":{"prop_1": "somevalue"} ),它不是在寻找什么是道具,它只是覆盖它。 我怎样才能绕过这个?

你的发现需要包括财产更新。 此外,更新声明需要位置更新操作符将其更改为(超出我的头):

 valuesToUpdate.prop = _.pick(req.body, 'prop_1', 'prop_2'); log.debug(JSON.stringify(valuesToUpdate)); User.update({$and : [{_id: req.params.id}, {prop.prop1 : "%oldvalue%"}]}, {$set: { "prop.$.prop1" : "%newvalue""}}) .then((data) => { return res.json({message: data}); }) .catch(err => { log.error(err); return next({message: 'Error updating User.'}); }); 

请注意位置更新只更新FIRST发生!

更新:重读你的问题后,我看到道具是不是一个数组…我很抱歉。 幸运的是,这使得它更容易:)

你不需要该字段出现在集合的查找中:{$ set:{“prop.prop1”:“newvalue”}位置更新也不是必需的,因为它不是一个数组。

这使得以下内容:

 valuesToUpdate.prop = _.pick(req.body, 'prop_1', 'prop_2'); log.debug(JSON.stringify(valuesToUpdate)); User.update({_id: req.params.id}, {$set: { "prop.prop1" : "%newvalue%"}}) .then((data) => { return res.json({message: data}); }) .catch(err => { log.error(err); return next({message: 'Error updating User.'}); }); 

UPDATE2:有关更新语句的更多信息。

由于评论的我会澄清更新命令。 当你想更新文档中的字段时,使用$ set命令。 这会更新一个或多个字段。 当你想更新多个领域,你可以使用如下命令:

 $set : { "prop.prop1" : "newvalueforprop1", "prop.prop2" : "newvalueforprop2"} } 

但是当你使用上面的命令并指定一个字段时,它会生成如下命令:

 $set : { "prop.prop1" : "newvalueforprop1", "prop.prop2" : null} } 

这是关于如何创build更新命令的全部内容。 当你不知道它是1或2属性,你需要更新你的代码,以便它dynamic地生成一个命令。 但是,你可以做的另一件事是让mongoose处理更新。

使用类似于:

 User.findById(req.params.id, function (err, user) { if (err) { handleError(err) } else { //you should to some checking if the supplied value is present (!= undefined) and if it differs from the currently stored one user.prop.prop1 = "your value"; user.prop.prop1 = "2nd value" user.save(function (err) { if (err) { handleError(err) } else { res.json(user); } }); } }); 

希望现在清楚。