Mongodb 使用默认文档mongo创建集合

Mongodb 使用默认文档mongo创建集合,mongodb,mongoose,Mongodb,Mongoose,我想在我的mongodb中创建名为“Admins”的集合。问题是,新的管理员只能由现有的管理员添加,但在初始状态下,我并没有任何管理员 创建新集合时,创建默认管理员最方便的方法是什么?我的模式是 const adminSchema = new Schema({ email: { type: String, required: true, unique: true, lowercase: true }, password: { type: Str

我想在我的mongodb中创建名为“Admins”的集合。问题是,新的管理员只能由现有的管理员添加,但在初始状态下,我并没有任何管理员

创建新集合时,创建默认管理员最方便的方法是什么?我的模式是

const adminSchema = new Schema({
  email: {
    type: String,
    required: true,
    unique: true,
    lowercase: true
  },
  password: {
    type: String,
    required: true,
    minlength: 4,
    maxlength: 128
  },
  name: {
    type: String,
    maxlength: 50
  }
}, {
  timestamps: true
})

您可以使用一个脚本,比如seed.js,根据需要安全地插入尽可能多的用户

            //seed.js
            var Admin = require('../path/to/admin.js');

            // you can refer any other flow to get count or number of record
            Admin.countDocuments({}, function( err, count){

                console.log( "Number of users:", count );

                // decide ur other logic

                // if count is 0 or less
                if(count <= 0) {

                    var user = {
                        name: "Admin User",
                        email: "admin@gmail.com",
                        password: "admin"
                    }

                    Admin.create(user, function(e) {
                        if (e) {
                            throw e;
                        }
                    });
                }

            })

希望这对你有帮助

您可以使用默认脚本,如果索引/应用程序文件中不存在记录,则可以添加记录。从代码段创建类似于
const Admin=new Admin(user)wait Admin.save()的记录。
?我想用Mongoose
count
user
保存到mongodb,也可以是常量,它应该是异步函数:D,但我不担心,谢谢
count
方法不推荐使用,应该使用
countDocuments
    try {


            // you can refer here any other method to get count or number of record
            let count = await Admin.countDocuments({});

            if(count <= 0) {
                var user = {
                    name: "Admin User",
                    email: "admin@gmail.com",
                    password: "admin"
                }
                const admin = new Admin(user);
                await admin.save()
            }

        } catch (err) {

            console.log(err);
        }
require('../path/to/seed');