【问题标题】:Query another model and add reference before findOneAndUpdate insert在 findOneAndUpdate 插入之前查询另一个模型并添加引用
【发布时间】:2019-09-22 05:05:48
【问题描述】:

我有一个模型 DotaStats,我正在尝试插入或更新,并使用 findOneAndUpdate 进行查找。该模型的新实例以这种方式创建,带有 upsert: true。

我发现我可以将虚拟对象用于我想在这个模型上做的很多计算工作,但我不确定的一件事是如何引用另一个模型(不提供 _id)新的创造。

我的用例是这样的,因为我不想在每个 findOneAndUpdate 请求中查询另一个模型(游戏模型),因为大多数时候这些请求只会被更新,而游戏参考不会有每次更新。

这是我的代码。这是模型:

let mongoose = require('mongoose');
const Game = require('../Game');

let Schema = mongoose.Schema;

let schemaOptions = {
    toObject: {
        virtuals: true
    },
    toJSON: {
        virtuals: true
    }
};

//NOTE: Validate URL!
let DotaStatsSchema = new Schema({
    user: {
        type: Schema.ObjectId,
        ref: 'User',
        unique: true,
        required: true
    },
    game: {
        type: Schema.ObjectId,
        ref: 'Game',
    },
    updatedAt: {
        type: Date,
        required: true
    },
    rank: {
        type: Number,
        default: 0
    },
    mmrEstimate: {
        type: Number,
        default: 0
    },
    wins: {
        type: Number,
        default: 0
    },
    losses: {
        type: Number,
        default: 0
    },
    winPercentage: {
        type: Number
    },
    kills: {
        type: Number,
        default: 0
    },
    deaths: {
        type: Number,
        default: 0
    },
    assists: {
        type: Number,
        default: 0
    },
    kda: {
        type: Number
    },
    secondsPlayed: {
        type: Number,
        default: 0
    }
}, schemaOptions);

DotaStatsSchema.virtual('winPercentage').get(() => {
    return (this.wins / (this.wins + this.losses) * 100) ? (this.wins / (this.wins + this.losses) * 100).toFixed(2) : 0;
})

DotaStatsSchema.virtual('kda').get(() => {
    return ((this.kills + this.assists) / this.deaths) ? ((this.kills + this.assists) / this.deaths).toFixed(2) : 0;
})

let DotaStats = module.exports = mongoose.model('DotaStats', DotaStatsSchema);

这就是我调用 findOneAndUpdate 的地方:

exports.handleDotaStats = (req, res, next) => {
    const newStats = {
        user: req.user._id,
        updatedAt: Date.now(),
        rank: req.body.rank,
        mmrEstimate: req.body.mmrEstimate,
        wins: req.body.wins,
        losses: req.body.losses,
        kills: req.body.kills,
        deaths: req.body.deaths,
        assists: req.body.assists,
        secondsPlayed: req.body.duration
    }

    DotaStats.findOneAndUpdate({
        user: req.user._id
    }, newStats, {
        upsert: true,
        new: true,
        rawResult: true
    }).then((stats) => {
        return res.json({
            success: true,
            message: 'Dota stats created, or updated, and found.',
            stats: stats
        })
    }).catch((err) => {
        res.send(err)
    })
}

我的理解是 findOneAndUpdate 不能使用 .pre('save') 或 .pre('validate') 方法,所以除了每次都查询之外,我还有其他选择吗?

谢谢!

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    关闭这个,找到一个足够体面的答案 - 使用 findOneAndUpdate 中提供的 rawResult(或 passRawResult)选项,您可以在请求后立即确定文档是否已被更新。现在已经足够了。

    【讨论】:

      猜你喜欢
      • 2019-05-24
      • 1970-01-01
      • 2012-01-25
      • 1970-01-01
      • 1970-01-01
      • 2012-06-13
      • 2015-01-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多