Deezer
Deezer

Reputation: 63

How can I add an user at start in nodejs?

I want to create a user if I start my connection to localhost and mongoDB but I don´t know how to do it I tried so many things but don´t know how to get an user at start.

so my Schema looks this way:

const UserSchema = mongoose.Schema({
    userID: {
        type: String,
        required: true
    },
    userName: {
        type: String,
        required: true
    },
    password: {
        type: String,
        required: true
    },
    isAdministrator: {
        required: Boolean
    }
});

And my connection is this:

const dbURI = "mongodb://localhost:27017/test";
mongoose.connect(dbURI, {
    useNewUrlParser: true,
    useUnifiedTopology: true
})
const db = mongoose.connection;

db.on("error", (err)=>{console.error(err)});
db.once("open", () => { console.log ("Database started successfully")})

Upvotes: 0

Views: 659

Answers (1)

Smit Gajera
Smit Gajera

Reputation: 1039

Use this user schema if you want to create a normal user-defined by default: false and if you want to create admin defined by default: true.

const UserSchema = mongoose.Schema({
  userID: {
    type: String,
    required: true,
  },
  userName: {
    type: String,
    required: true,
  },
  password: {
    type: String,
    required: true,
  },
  isAdministrator: {
    required: Boolean,
    default: false,
  },
});

Upvotes: 1

Related Questions