【发布时间】:2018-12-20 01:35:54
【问题描述】:
我有一个案例,我使用 mongoose .pre('save') 挂钩将一些数据非规范化到其他文档。我正在努力寻找一个好的解决方案来更新数据并在整个数据库中保持非规范化一致。如果我想更新文档,我会考虑三种选择:
- 执行原子更新
我不想这样做的原因是它不会触发我需要对数据进行非规范化的 mongoose 中间件。
- 使用
.post('update')钩子
这种方法的问题在于我无法在挂钩中判断哪些字段已更新,对吧?那么我应该假设所有字段都已更新并对整个数据库中的数据进行非规范化吗?看起来很激烈。
- 获取文档,修改,然后保存
这似乎很方便,但会带来覆盖数据的风险,即如果要在“介于”时刻的其他地方更新文档。
在 models/car.model.js:
const { mongoose } = require('mongoose');
const Schema = mongoose.Schema;
const Manufacturer = require('./manufacturer.model.js');
const CarSchema = new Schema({
name: String,
manufacturer: {
type: {
_id: Schema.Types.ObjectId,
name: String,
},
},
});
CarSchema.pre('save', async function(next) {
/*
if (this.isModified('name')) {
await Manufacturer.findByIdAndUpdate(this.manufacturer, {
$set: {
car-name: this.name,
},
});
}
*/
if (this.isModified('manufacturer') {
const manufacturer = await Manufacturer.findOne({
_id: this.manufacturer._id,
}, {
name: 1,
});
this.manufacturer.name = manufacturer.name;
}
});
在 controllers/car.controller.js:
app.patch('/:id', async function (req, res, next) {
const car = await Car.findById(req.params.id);
// Bad solution, helps please
for (var key in req.body) {
car[key] = req.body[key];
}
await car.save();
res.sendStatus(200);
});
有什么解决方案可以两全其美?
【问题讨论】: