Incrementing a value with mongoose?

生来就可爱ヽ(ⅴ<●) 提交于 2020-12-29 13:11:59

问题


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

回答1:


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.




回答2:


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


});

// next is the field , type: Number




回答3:


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



回答4:


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


});


来源:https://stackoverflow.com/questions/8987372/incrementing-a-value-with-mongoose

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!