node.js 猫鼬 Model.update() - 只更新提供的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40466323/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
mongoose Model.update() - only update provided values
提问by Miha ?u?ter?i?
I have the following schema:
我有以下架构:
const wordSchema = mongoose.Schema({
author: {type: String, index: true, default: 'unknown'},
quote: String,
source: {type: String, default: 'unknown', index: true},
rating: {type: Number, default: 0},
createdAt: {type: Date, default: Date.now},
updatedAt: {type: Date, default: Date.now},
});
And the following PUT route in my express app:
以及我的快递应用程序中的以下 PUT 路线:
// Route to update a quote in the DB
app.put('/words/:id', function(req, res) {
const quote = new Word({
_id: req.params.id,
author: req.body.author,
quote: req.body.quote,
source: req.body.source,
rating: req.body.rating,
updatedAt: Date.now(),
});
Word.update(quote, function(err, raw) {
if (err) {
res.send(err);
}
res.send(raw);
});
});
Now when I send the PUT request, if the parameters set with a default value are not provided, they will be filled with the default values from the Schema. How do I update only the provided values?
现在,当我发送 PUT 请求时,如果未提供使用默认值设置的参数,则将使用 Schema 中的默认值填充它们。如何仅更新提供的值?
Thanks for the help.
谢谢您的帮助。
回答by JohnnyHK
Don't create a new Wordinstance for the update, updatetakes conditions and doc object parameters that let you separately identify the document to update and provide its updated values:
不要Word为更新创建新实例,update采用条件和 doc 对象参数,让您单独标识要更新的文档并提供其更新值:
app.put('/words/:id', function(req, res) {
const doc = {
author: req.body.author,
quote: req.body.quote,
source: req.body.source,
rating: req.body.rating,
updatedAt: Date.now(),
});
Word.update({_id: req.params.id}, doc, function(err, raw) {
if (err) {
res.send(err);
}
res.send(raw);
});
});
回答by chridam
You can try using the Model.findByIdAndUpdate()method where all top level update keys which are not atomic operation names are treated as set operations and defaults/setters are never executed. You can use lodash's _.assign()method to set the updatedAtfield:
您可以尝试使用Model.findByIdAndUpdate()所有不是原子操作名称的顶级更新键都被视为设置操作并且从不执行默认值/设置器的方法。您可以使用 lodash 的_.assign()方法来设置updatedAt字段:
// Route to update a quote in the DB
app.put('/words/:id', function(req, res) {
const update = _.assign({ "updatedAt": new Date() }, req.body);
Word.findByIdAndUpdate(req.params.id, update, function(err, raw) {
if (err) {
res.send(err);
}
res.send(raw);
});
});

