Industrial
Industrial

Reputation: 42758

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

Upvotes: 5

Views: 18308

Answers (4)

Anthony
Anthony

Reputation: 14269

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) {


});

Upvotes: 0

keithics
keithics

Reputation: 8758

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


});

// next is the field , type: Number

Upvotes: 27

alessioalex
alessioalex

Reputation: 63653

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.

Upvotes: 4

ManInTheBox
ManInTheBox

Reputation: 174

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

Upvotes: 1

Related Questions