gpt4 book ai didi

node.js - mongoose Model.update() - 仅更新提供的值

转载 作者:太空宇宙 更新时间:2023-11-03 22:40:44 25 4
gpt4 key购买 nike

我有以下架构:

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},
});

以及我的 Express 应用程序中的以下 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);
});
});

现在,当我发送 PUT 请求时,如果未提供设置默认值的参数,它们将使用架构中的默认值填充。如何仅更新提供的值?

感谢您的帮助。

最佳答案

不要为更新创建新的 Word 实例,update接受条件和文档对象参数,使您可以单独识别要更新的文档并提供其更新值:

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);
});
});

关于node.js - mongoose Model.update() - 仅更新提供的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40466323/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com