5

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
});
Industrial
  • 41,400
  • 69
  • 194
  • 289

4 Answers4

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


});

// next is the field , type: Number

JoeTidee
  • 24,754
  • 25
  • 104
  • 149
keithics
  • 8,576
  • 2
  • 48
  • 35
  • 1
    For the title of the question, this is the answer most people will be looking for. – tbh__ Jan 15 '17 at 03:06
  • If you need to increment a document field, you can use `your_doc.update({$inc: {next:1}})` directly. [Doc here](http://mongoosejs.com/docs/api.html#document_Document-update) – lifeisfoo Jul 25 '17 at 15:33
4

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.

alessioalex
  • 62,577
  • 16
  • 155
  • 122
1

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
});
ManInTheBox
  • 174
  • 1
  • 2
  • 7
0

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


});
Anthony
  • 13,434
  • 14
  • 60
  • 80