用mongoose增加一个值?
我的node.js
应用程序中有一个mongoose
模型,代表发票。 我已经算出了大部分,但我真的需要确保我的发票被编/递增,以便能够为我的客户提供适当的参考。
使用SQL数据库,我会创build一个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 });
通常在MongoDB中,不会为_id(或其他字段)使用自动增量模式,因为这在大型数据库群集上不能很好地扩展。 而是通常使用对象ID。
欲了解更多信息结帐此链接: http : //www.mongodb.org/display/DOCS/How+to+Make+an+Auto+Incrementing+Field
所以底线你可以使用对象ID,这是唯一的。
Controller.findByIdAndUpdate(ID_HERE, {$inc: {next:1}}, function (err, data) { });
//接下来是字段,input:Number
这是你在找什么?
比方说, UserSchema
和InvoiceSchema
看起来像这样:
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 });
对基思的答案嗤之以鼻:
您可以添加一个额外的对象,以确保在增加后接收文档,因此,我使用lean()和exec()来确保文档是一个纯JavaScript对象:
Controller.findByIdAndUpdate(ID_HERE, {$inc: {next:1}}, { $new: true}) .lean().exec(function (err, data) { });