简体   繁体   English

MongoDB 自动递增作为新用户的 ID

[英]MongoDB Auto increment as ID for new users

I'm working on a small Web-API project using MongoDB.我正在使用 MongoDB 开发一个小型 Web-API 项目。 As far as I know, MongoDB uses _id:UnixDateETC but I want a ID that like in MySQL or MSQL is able to autoincrement each time a new user is created.据我所知,MongoDB 使用 _id:UnixDateETC 但我想要一个像 MySQL 或 MSQL 一样的 ID,每次创建新用户时都能够自动递增。 I played around with the "find().count()", found some attemps on the internet, but none of what I tried seem to work.我玩弄了“find().count()”,在互联网上找到了一些尝试,但我尝试过的似乎都不起作用。 I'm not quite sure if I'm doing it wrong or if it's not possible by doing such thing like I tried them.我不太确定是我做错了,还是像我尝试过的那样做这样的事情是不可能的。 ( My attempt can be found under "models/user.js":id) (我的尝试可以在“models/user.js”下找到:id)

Any suggestions how I directly can go into the schema, count it's entries and than add it to the new record without any complicated new seperate function ?有什么建议我可以直接进入模式,计算它的条目,然后将其添加到新记录中,而不需要任何复杂的新单独功能吗? The reason for that is that I'm trying to hold the models clean/readable.原因是我试图保持模型干净/可读。

Thanks in advance.提前致谢。

routes/user.js:路线/user.js:

let mongoose = require('mongoose');
let User = require('../models/user');
var config = require('../configs/config');
var jwt = require('jsonwebtoken');
var bcrypt = require('bcryptjs');


function userRegistration(req, res) {
    var hashedPassword = bcrypt.hashSync(req.body.psw, 10);
    var user = new User(req.body);
    user.psw = hashedPassword;
        user.save(function (err) {      
            if (err) return res.status(500).send("There was a problem registering the user.");
            var token = jwt.sign({ id: user.userName }, config.secret, {
                    expiresIn: 86400 // expires in 24 hours
            });
                  res.status(200).send({ auth: true, token: token });        
  });
}

//export all the functions
module.exports = { userRegistration };

models/user.js:模型/user.js:

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


var UserSchema = new Schema({
    id: this.db.id.find().count() + 1,
    userName: String,
    psw: String,
    email: String , 
    active : Boolean
});




module.exports = mongoose.model('User', UserSchema);

Got it to work.得到它的工作。

What I had to do was to create a preSave in my "/models/user.js"我必须做的是在我的“/models/user.js”中创建一个 preSave

model/user.js:模型/用户.js:

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


var UserSchema = new Schema({
    id: Number,
    userName: String,
    psw: String,
    email: String , 
    active : Boolean
});


UserSchema.pre("save", function(next){
    var docs = this;
    mongoose.model('User', UserSchema).countDocuments(function(error, counter){
        if(error) return next(error);
        docs.id = counter+1;
        next();
    });   
});

##Edit 02.07.2021: Note that this solution only works aslong u clear or keep instead of deleting your document(s). ##Edit 02.07.2021:请注意,此解决方案仅适用于您清除或保留而不是删除您的文档。 Otherwise u will end up with duplicate ID's since I count the number of currently existing documents.否则你最终会得到重复的 ID,因为我计算了当前存在的文档数量。 Back then my final solution was to store a counter/value in another collection/table and increment it each time a new document gets created to keep track of my id(s).当时我的最终解决方案是在另一个集合/表中存储一个计数器/值,并在每次创建新文档时增加它以跟踪我的 id(s)。 This newly incremented value will then be used in our preSave instead of counting documents...这个新增加的值将在我们的 preSave 中使用,而不是计算文档......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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