【问题标题】:Mongoose unique value per day猫鼬每天的独特价值
【发布时间】:2019-01-14 03:50:12
【问题描述】:

我正在尝试配置猫鼬模式唯一参数。我需要每天允许写入数据库的唯一作者不超过一位。 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.js mongoose


    【解决方案1】:

    您可以使用 $setOnInsertupsert 选项进行更新操作,即如果 update()upsert: 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)
        }
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-07-22
      • 2018-09-30
      • 2014-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-24
      • 1970-01-01
      相关资源
      最近更新 更多