I have a mongoose
model in my node.js
application, representing invoices. I have figured most of it out already, but I really need to ensure that my invoices are numerated/incremented to be able to provide a proper reference to my customer.
Using an SQL database, I would have created an AUTO-INCREMENT
column holding this value, but this obviosly isn't built into MongoDB. So how would I accomplish this with mongoose
?
Here's how my model looks right now:
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
});
To increment a number field value in Mongoose, you can use the $inc operator. This operator increments a field by a specified value.
Mongoose plugin that auto-increments any ID field on your schema every time a document is saved. This is the module used by mongoose-simpledb to increment Number IDs. You are perfectly able to use this module by itself if you would like.
For example, if we want every document where the value of the name field is more than one value, then what? For such cases, mongoose provides the $in operator. In this article, we will discuss how to use $in operator. We will use the $in method on the kennel collection.
_id field is auto generated by Mongoose and gets attached to the Model, and at the time of saving/inserting the document into MongoDB, MongoDB will use that unique _id field which was generated by Mongoose.
Controller.findByIdAndUpdate(ID_HERE, {$inc: {next:1}}, function (err, data) {
});
// next is the field , type: Number
Generally in MongoDB, one does not use an auto-increment pattern for _id's (or other fields), as this does not scale up well on large database clusters. Instead one typically uses Object IDs.
For more info checkout this link: http://www.mongodb.org/display/DOCS/How+to+Make+an+Auto+Incrementing+Field
So bottom line you can just use Object IDs, those are unique.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With