vic*_*rsa 6 mongoose node.js mongoose-schema
我正在处理一个项目,在该项目中,我需要在一个模型中根据另一个字段值设置一个字段的值。让我用一些代码解释一下。
Destination model
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const DestinationSchema = new Schema({
name: {
type: String,
required: true
},
priority: {
type: Number,
default: 0,
max: 10,
required: true
}
})
DestinationSchema.statics.getPriority = function(value) {
return this.findOne({ _id: value })
}
const Destination = mongoose.model('Destination', DestinationSchema)
exports.Destination = Destination
Run Code Online (Sandbox Code Playgroud)
Task model
const mongoose = require('mongoose')
const { Destination } = require('../_models/destination.model')
const Schema = mongoose.Schema;
const TaskSchema = new Schema({
priority: {
type: Number,
required: true,
min: 0,
max: 25
},
from: {
type: Schema.Types.ObjectId,
ref: 'Destination',
required: true
},
to: {
type: Schema.Types.ObjectId,
ref: 'Destination',
required: true
},
type: {
type: Number,
required: true,
min: 0,
max: 3
}
}, {
timestamps: true
})
TaskSchema.pre('save', async function () {
this.priority = await Destination.getPriority(this.from).then(doc => {
return doc.priority
})
this.priority += await Destination.getPriority(this.to).then(doc => {
return doc.priority
})
this.priority += this.type
})
Run Code Online (Sandbox Code Playgroud)
Task Controller update function
exports.update = async function (req, res) {
try {
await Task.findOneAndUpdate({
_id: req.task._id
}, { $set: req.body }, {
new: true,
context: 'query'
})
.then(task =>
sendSuccess(res, 201, 'Task updated.')({
task
}),
throwError(500, 'sequelize error')
)
} catch (e) {
sendError(res)(e)
}
}
Run Code Online (Sandbox Code Playgroud)
当我创建一个新任务时,优先级会按预期在预保存挂钩中设置。但是当我需要更改Task.from或更改Task.to为另一个时我碰壁了destination,然后我需要再次重新计算任务优先级。我可以在客户端执行此操作,但这会导致一个问题,即人们可以简单地将priority更新查询发送到服务器。
我的问题是,Task当a使用fromand 的新值更新时,如何计算 a 的优先级to?我是否必须查询即将更新的文档以获取对它的引用,或者是否有另一种更简洁的方法来做到这一点,因为这会导致对数据库的额外命中,我试图避免它越多越好。
小智 0
在您的任务架构中。
你必须使用pre("findOneAndUpdate")猫鼬中间件。它允许您在执行更新查询之前对其进行修改
试试这个代码:
TaskSchema.pre('findOneAndUpdate', async function(next) {
if(this._update.from || this._update.to) {
if(this._update.from) {
this._update.priority = await Destination.getPriority(this._update.from).then(doc => {
return doc.priority
});
}
if(this._update.to) {
this._update.priority += await Destination.getPriority(this._update.to).then(doc => {
return doc.priority
});
}
}
next();
});
Run Code Online (Sandbox Code Playgroud)