Create unique autoincrement field with mongoose

亡梦爱人 提交于 2019-11-26 16:32:51

问题


Given a Schema:

var EventSchema = new Schema({
    id: {
        // ...
    },
    name: {
        type: String
    },
});

I want to make id unique and autoincrement. I try to realize mongodb implementation but have problems of understanding how to do it right in mongoose.

My question is: what is the right way to implement autoincrement field in mongoose without using any plugins and so on?


回答1:


Here is a good example of auto-incremented fields implementation using Mongoose:

var CounterSchema = Schema({
    _id: {type: String, required: true},
    seq: { type: Number, default: 0 }
});
var counter = mongoose.model('counter', CounterSchema);

var entitySchema = mongoose.Schema({
    testvalue: {type: String}
});

entitySchema.pre('save', function(next) {
    var doc = this;
    counter.findByIdAndUpdate({_id: 'entityId'}, {$inc: { seq: 1} }, function(error, counter)   {
        if(error)
            return next(error);
        doc.testvalue = counter.seq;
        next();
    });
});

You should perform the Step 1 from mongodb documentation firstly.




回答2:


You can use this. This package every time generate unique value for this.

Package Name : uniqid

Link : https://www.npmjs.com/package/uniqid




回答3:


Yes, here's the "skinny" on that feature.

You need to have that collection in your mongo database. It acts as concurrent key allocation single record of truth if you want. Mongo's example shows you how to perform an "atomic" operation to get the next key and ensure that even there are concurrent requests you will be guaranteed to have the unique key returned without collisions.

But, mongodb doesn't implement that mechanism natively, they show you how to do it. They only provide for the _id to be used as unique document key. I hope this clarifies your approach.

To expand on the idea, go ahead and add that mongo suggested implementation to your defined Mongoose model and as you already guessed, use it in Pre-save or better yet pre-init event to ensure you always generate an id if you work with a collection server side before you save it to mongo.




回答4:


Other way is you can use external packages given by mongoose.

mongoose sequence plugin

mongoose auto increment plugin




回答5:


Ignore all the above. Here is the solution

YourModelname.find().count(function(err, count){
   req["body"].yourID= count + 1;
      YourModelname.create(req.body, function (err, post) {
        if (err) return next(err);
        res.json(req.body);
      });
    });


来源:https://stackoverflow.com/questions/23199482/create-unique-autoincrement-field-with-mongoose

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