在猫鼬中,根据findOneAndUpdate

时间:2019-02-21 12:46:44

标签: node.js mongoose 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

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

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

当我创建一个新任务时,可以在预保存钩子中设置优先级,正如预期的那样。但是当我需要将Task.fromTask.to更改为另一个destination时遇到了麻烦,然后我需要重新计算任务优先级。我可以在客户端执行此操作,但这会引起一种担忧,即人们可能只是将更新查询中的priority发送到服务器。

我的问题是,Taskfromto的新值更新时,如何计算优先级?我是否必须查询将要更新的文档以获得对它的引用,或者是否有另一种更清洁的方法来执行它,因为这会导致对数据库的另一次打击,因此我试图避免它尽可能地。

0 个答案:

没有答案