简体   繁体   中英

Auto increment sequence in Mongoose

I am trying to implement Auto increment in uisng mongoose. But I am stuck.

Counter Schema

counter.js

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var counterSchema = new Schema({
    _id: {type: String, required: true},
    sequence_value: {type: Number, default: 1}
});

var Counter = module.exports = mongoose.model('Counter', counterSchema);

Product Schema

products.js

var productsSchema = new Schema({
    productId: {type: String, require: false},
    merchantId: {type: String, required: false}
)}

I have created counter collection and inserted one record inside it.

{
    "_id" : "productId",
    "sequence_value" : 1
}

Include method to increment the counter in the counter collection

//COUNTER COLLECTION
function getNextSequenceValue(sequenceName){

   var sequenceDocument = Counters.findOneAndUpdate({
      query:{_id: sequenceName },
      update: {$inc:{sequence_value:1}},
      new:true
   });

   return sequenceDocument.sequence_value;
}

Calling method to increment sequence number:

product.productId = getNextSequenceValue("productid");

But it's not working, nothing is getting saved in the products collection?

the next sequence should be

product.productId = getNextSequenceValue("productId"); // camelCase

in the counter collection you have added document with key productId (camelCase) but trying to get sequence with key productid (all lowercase)

mongo CLI

> function getNextSequenceValue(sequenceName){
... 
...    var sequenceDocument = db.counters.findOneAndUpdate(
...       { "_id" : sequenceName },
...       { $inc : { sequence_value : 1 } },
...       { new : true }
...    );
...    return sequenceDocument.sequence_value;
... }
> 

EDIT-2 with mongoose

var counterSchema = mongoose.Schema(
    {
        _id: { type: String, required: true },
        sequence_value: { type: Number, default: 1 }
    }
);

var Counters = mongoose.model('Counters', counterSchema);

var productsSchema = mongoose.Schema({
    productId: {type: String, require: true},
    merchantId: {type: String, required: false}
});

productsSchema.pre('save', function(next){
    var doc = this;
    Counters.findOneAndUpdate(
        { _id: 'productId' },
        { $inc : { sequence_value : 1 } },
        { new : true },  
        function(err, seq){
            if(err) return next(err);
            doc.productId = seq.sequence_value;
            next();
        }
    );
 }
);

var Product = mongoose.model('Product', productsSchema);
var testProduct = new Product({merchantId : 'test'})

testProduct.save(function (err, doc){
    console.log('saved ' + doc )
})

output (with generated productId)

saravana@ubuntu:~/node-mongoose$ node app.js
`open()` is deprecated in mongoose >= 4.11.0, use `openUri()` instead, or set the `useMongoClient` option if using `connect()` or `createConnection()`. See http://mongoosejs.com/docs/connections.html#use-mongo-client
Mongoose: counters.findAndModify({ _id: 'productId' }, [], { '$inc': { sequence_value: 1 } }, { new: true, upsert: false, remove: false, fields: {} })
Mongoose: products.insert({ productId: '36', merchantId: 'test', _id: ObjectId("5a5b27b860716d24007df611"), __v: 0 })
saved { __v: 0,
  productId: '36',
  merchantId: 'test',
  _id: 5a5b27b860716d24007df611 }
^C
saravana@ubuntu:~/node-mongoose$

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM