BT101
BT101

Reputation: 3826

Create collection with default document mongo

I want to create collection named "Admins" in my mongodb. Problem is that new admins can be added only by already existing admin but on initial state I don't have any admins.

What is most convienient way to create default admin when creating new collection? My schema is

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

Upvotes: 2

Views: 1405

Answers (1)

Santosh Shinde
Santosh Shinde

Reputation: 6063

You can use a script, say seed.js, to safely insert as many users as required.

            //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: "[email protected]",
                        password: "admin"
                    }

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

            })

With latest approach you can may use following way

    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: "[email protected]",
                    password: "admin"
                }
                const admin = new Admin(user);
                await admin.save()
            }

        } catch (err) {

            console.log(err);
        }

Require seed.js in your server.js or app.js script right after the connection to mongodb is made. Comment or remove this line when you are done seeding.

require('../path/to/seed');

Hope this will help you !

Upvotes: 2

Related Questions