用猫鼬增加一个值?

时间:2012-01-24 13:11:05

标签: node.js express mongoose

我的mongoose应用程序中有一个node.js模型,代表发票。我已经想出了大部分内容,但我确实需要确保我的发票被计算/递增以便能够为我的客户提供适当的参考。

使用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
});

3 个答案:

答案 0 :(得分:26)

Controller.findByIdAndUpdate(ID_HERE, {$inc: {next:1}}, function (err, data) {


});

// next是字段,输入:Number

答案 1 :(得分:4)

  

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

有关详情,请访问以下链接:http://www.mongodb.org/display/DOCS/How+to+Make+an+Auto+Incrementing+Field

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

答案 2 :(得分:1)

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
});