【问题标题】:increment a field in moongose在猫鼬中增加一个字段
【发布时间】:2019-12-05 19:39:33
【问题描述】:

我想根据条件在更新时自动增加一个字段。

我有两个架构:

var History = new Schema({
   action : {type: String},
   eventType : {type : String}
})

还有:

 var Quote = new Schema({
           name : {type: String},
           email : {type: String},
           quoteNumber : {type: Number}
           history: [History]
        });

quoteNumber 是我希望在记录 histroy 字段更新后立即递增 1 的字段。

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    您将在 MongoDB 中使用 $inc 运算符。因此,无论您使用哪个函数来更新历史记录,例如:

    db.collection.update({name: "foo"}, {$push: {history: "Log History"}, $inc:{quoteNumber : 1})
    

    在此处阅读:https://docs.mongodb.com/manual/reference/operator/update/inc/

    然而,由于历史是一个数组,你也可以得到数组的长度。

    【讨论】:

      猜你喜欢
      • 2012-02-17
      • 2018-06-23
      • 1970-01-01
      • 2014-06-10
      • 2020-10-15
      • 2018-04-29
      • 1970-01-01
      • 2018-01-05
      • 2017-06-01
      相关资源
      最近更新 更多