2012-01-24 92 views
5

我在我的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 
}); 

回答

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 
}); 
24
Controller.findByIdAndUpdate(ID_HERE, {$inc: {next:1}}, function (err, data) { 


}); 

//其次是字段中,鍵入:數

+0

正是我在找的東西。謝謝! – danyim

+0

完美 - 謝謝! – JoeTidee

+0

對於問題的標題,這是大多數人會尋找的答案。 –

0

Riffing上keithic的回答是:

您可以添加額外的對象,以確保接收文件後,它一直在增加,因此,我使用lean()和exec()來確保文檔是一個純Javascript對象:

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


});