【问题标题】:Incrementing a value with mongoose?用猫鼬增加一个值?
【发布时间】:2012-02-17 17:33:25
【问题描述】:

我的node.js 应用程序中有一个mongoose 模型,代表发票。我已经弄清楚了大部分,但我真的需要确保我的发票被编号/递增,以便能够为我的客户提供适当的参考。

使用 SQL 数据库,我会创建一个 AUTO-INCREMENT 列来保存这个值,但这显然不是 MongoDB 内置的。那么我将如何使用mongoose 完成此操作?

这是我的模型现在的样子:

var InvoiceSchema = new Schema({
    reference: {type: Number, default: 0}, // The property I want to auto-incr.

    dates: {
        created:  {type: Date, default: Date.now},
        expire: {type: Date, default: expiryDate()}
    },

    amount: {type: Number, default: 0}
    // And so on
});

【问题讨论】:

    标签: node.js express mongoose


    【解决方案1】:
    Controller.findByIdAndUpdate(ID_HERE, {$inc: {next:1}}, function (err, data) {
    
    
    });
    

    //下一个是字段,输入:数字

    【讨论】:

    • 对于问题的标题,这是大多数人会寻找的答案。
    • 如果需要增加文档字段,可以直接使用your_doc.update({$inc: {next:1}})Doc here
    【解决方案2】:

    通常在 MongoDB 中,不使用自增模式 _id(或其他字段),因为这在大型数据库集群上不能很好地扩展。相反,通常使用对象 ID。

    欲了解更多信息,请查看此链接:http://www.mongodb.org/display/DOCS/How+to+Make+an+Auto+Incrementing+Field

    所以底线你可以只使用对象 ID,它们是唯一的。

    【讨论】:

      【解决方案3】:

      this 你在找什么?

      假设UserSchemaInvoiceSchema 看起来像这样:

      var UserSchema = new Schema({
          email: String,
          // other fields
          invoices: [{ type: Schema.Objectid, ref: 'Invoice' }]
      });
      
      var InvoiceSchema = new Schema({
          reference: { type: Schema.Objectid, ref: 'User' },
      
          dates: {
              created:  {type: Date, default: Date.now},
              expire: {type: Date, default: expiryDate()},
          },
      
          amount: {type: Number, default: 0}
          // And so on
      });
      

      【讨论】:

        【解决方案4】:

        重复 keithic 的回答:

        您可以添加一个额外的对象以确保在文档增加后接收它,因此,我使用lea() 和 exec() 来确保文档是一个普通的 Javascript 对象:

        Controller.findByIdAndUpdate(ID_HERE, {$inc: {next:1}}, { $new: true})
           .lean().exec(function (err, data) {
        
        
        });
        

        【讨论】:

          猜你喜欢
          • 2018-04-29
          • 1970-01-01
          • 1970-01-01
          • 2021-06-07
          • 2015-04-06
          • 2020-10-15
          相关资源
          最近更新 更多