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

Answers


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.


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


});

// next is the field , type: Number


Is this what you looking for?

Let's say UserSchema and InvoiceSchema looks like this:

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

Riffing on keithic's answer:

You can add an additional object to make sure to receive the document AFTER it's been incremented, as such, I am using lean() and exec() to make sure the document is a plain Javascript object:

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


});

Need Your Help

Scrollable canvas inside div

javascript jquery html css html5

I have a html5 canvas. I need to show the fixed portion of it in the div(Div1). When I swipe inside Div1, I need to scroll the canvas. So as I scroll, I'll see corresponding part of the canvas.