首页 > 解决方案 > 猫鼬每天的独特价值

问题描述

我正在尝试配置猫鼬模式唯一参数。我需要每天允许写入数据库的唯一作者不超过一位。Schema.index( { author: 1, created: 1 } , { unique: true} ) 不起作用,这里我无法输入时间段。

有什么更好的方法来决定这个案子?

const Report = new Schema({
  author: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'DiscordUserList',
    required: true
  },
  reports: [{ reportNum: { type: Number }, text: { type: String }, date: { type: Date, default: Date.now } }],
  questionsDone: [{ questionNum: { type: Number }, done: { type: Boolean }, date: { type: Date, default: Date.now } }],
  created: {
    type: Date,
    default: Date.now
  }
}, { strict: false })
Report.plugin(mongoosePaginate)



const reportListSchema = mongoose.model('ReportList', Report)


module.exports = reportListSchema

标签: node.jsmongoose

解决方案


您可以使用$setOnInsertandupsert选项进行更新操作,即如果update()withupsert: true找到了匹配的文档,则 MongoDB 执行更新,应用该$set操作但忽略该$setOnInsert操作。因此,您的典型更新如下:

import moment from 'moment'

const start = moment().startOf('day').toDate() // set to 12:00 am today
const end = moment().endOf('day').toDate() // set to 23:59 pm today
ReportList.findOneAndUpdate(
    { 
        'author': author_id, 
        'created': { '$gte': start, '$lte': end }
    },
    {
        '$set': { 'author': author_id },
        '$setOnInsert': { 'created': moment().toDate() }
    },
    { 'upsert': true, 'new': true },
    (err, report) => {
        console.log(report)
    }
)

或者使用setDefaultsOnInsert当这个和upsert为真时的选项,如果创建新文档,猫鼬将应用模型模式中指定的默认值:

ReportList.findOneAndUpdate(
    { 
        'author': author_id, 
        'created': { '$gte': start, '$lte': end }
    },
    { '$set': { 'author': author_id } },
    { 
        'upsert': true, 
        'new': true, 
        'setDefaultsOnInsert': true 
    },
    (err, report) => {
        console.log(report)
    }
)

推荐阅读