node.js 使用猫鼬创建唯一的自动增量字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23199482/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 17:10:48  来源:igfitidea点击:

Create unique autoincrement field with mongoose

node.jsmongodbmongooseauto-incrementdatabase

提问by Glen Swift

Given a Schema:

给定一个架构:

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

I want to make idunique and autoincrement. I try to realize mongodb implementationbut have problems of understanding how to do it right in mongoose.

我想制作id唯一和自动增量。我尝试实现mongodb 实现,但在理解如何在 mongoose 中正确实现时遇到问题。

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

我的问题是:在不使用任何插件等的情况下,在 mongoose 中实现自动增量字段的正确方法什么?

回答by Biba

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.

您需要在 mongo 数据库中拥有该集合。如果您愿意,它可以充当并发密钥分配单个真实记录。Mongo 的示例向您展示了如何执行“原子”操作来获取下一个键,并确保即使存在并发请求,您也可以保证在没有冲突的情况下返回唯一键。

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.

但是,mongodb 本身并没有实现该机制,它们向您展示了如何实现。它们仅提供 _id 用作唯一文档密钥。我希望这可以澄清您的方法。

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.

为了扩展这个想法,继续将 mongo 建议的实现添加到您定义的 Mongoose 模型中,正如您已经猜到的,在 Pre-save 或更好的 pre-init 事件中使用它,以确保如果您使用在将其保存到 mongo 之前收集服务器端。

回答by Dhaval Mojidra

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

你可以用这个。这个包每次都会为此产生独特的价值。

Package Name : uniqid

包名:uniqid

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

链接:https: //www.npmjs.com/package/uniqid

回答by Natali

const ModelIncrementSchema = new Schema({
    model: { type: String, required: true, index: { unique: true } },
    idx: { type: Number, default: 0 }
});

ModelIncrementSchema.statics.getNextId = async function(modelName, callback) {
    let incr = await this.findOne({ model: modelName });

    if (!incr) incr = await new this({ model: modelName }).save();
    incr.idx++;
    incr.save();
    return incr.idx;
};


const PageSchema = new Schema({
    id: { type: Number ,  default: 0},
    title: { type: String },
    description: { type: String }
});


PageSchema.pre('save', async function(next) {
    if (this.isNew) {
        const id = await ModelIncrement.getNextId('Page');
        this.id = id; // Incremented
        next();
    } else {
        next();
    }
});

回答by Devarapalli Gopi

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