gpt4 book ai didi

node.js - 从请求正文更新 Mongoose 文档对象的字段

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

问题( Mongoose save all parameters from request body )展示了如何在一行代码中创建带有请求正文的新 Mongoose 文档对象。
扩展这个问题,我想知道如何一次设置 Mongoose 文档对象的所有字段。

router.route('/car')
.put(function(req, res, next) {
Car.findById(req.params.id, function (err, car) {
if (err) {
res.status(400).send(err);
} else {
if (!car)
return next(new Error('Failed to load car: ' + req.params.id));

car.name = req.body.name; // Code refactoring required
car.seats = req.body.seats;
car.engine_size = req.body.engine_size;

car.save(function(err) {
if(err)
res.status(400).send(err);
else
res.json(car);
});
}
});
});

在创建文档时var car = new Car(req.body);是填充请求正文中字段的完美方法。
为了更新现有的 Mongoose 文档,有没有比下面几行更好的方法:

car.name = req.body.name;
car.seats = req.body.seats;
car.engine_size = req.body.engine_size;

最佳答案

您应该使用更新而不是查找。

router.route('/car')
.put(function(req, res, next) {
Car.update({ _id: mongoose.Types.ObjectId(req.params.id) },req.body)
.then(function (success) {
res.json();
})
.catch(function (error) {
res.status(404).send(err);
});
});

关于node.js - 从请求正文更新 Mongoose 文档对象的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36951213/

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