Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incrementing a value with mongoose?

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
});
like image 991
Industrial Avatar asked Jan 24 '12 13:01

Industrial


People also ask

How do I increment a number value in Mongoose?

To increment a number field value in Mongoose, you can use the $inc operator. This operator increments a field by a specified value.

What is Mongoose auto increment?

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.

Can I use $in in Mongoose?

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.

Does Mongoose auto generate ID?

_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.


2 Answers

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


});

// next is the field , type: Number

like image 181
keithics Avatar answered Nov 15 '22 07:11

keithics


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.

like image 33
alessioalex Avatar answered Nov 15 '22 06:11

alessioalex