Skip to content

Instantly share code, notes, and snippets.

@aadilmallick
Created July 17, 2023 16:11
Show Gist options
  • Save aadilmallick/f204c9e66ab82ef43ec9aff75a12267b to your computer and use it in GitHub Desktop.
Save aadilmallick/f204c9e66ab82ef43ec9aff75a12267b to your computer and use it in GitHub Desktop.
Express App setup snippets

Express app

Mongoose database connection

const mongoose = require("mongoose");

const connectDB = async () => {
  try {
    mongoose.set("strictQuery", true);
    const password = "password";
    const database = "database_name";
    const conn = await mongoose.connect(
      `mongodb+srv://aadilmallick:${password}@cluster0.kqerb.mongodb.net/${database}`
    );
    console.log("connected!");
  } catch (e) {
    console.log(e);
  }
};

module.exports = { connectDB };

Mongoose schema

const mongoose = require("mongoose");

const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    lowercase: true,
    minLength: 2,
    maxLength: 25,
  },
  createdAt: {
    type: Date,
    immutable: true,
    default: () => Date.now(),
  },
  age: {
    type: Number,
    min: 1,
    max: 100,
  },
  email: {
    type: String,
    validate: {
      validator: (e) => e.includes("@"),
      message: (props) => `${props.value} is not a valid email`,
    },
  },
  bestFriend: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "User",
  },
});

const User = mongoose.model("User", userSchema);

module.exports = User;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment