Mongoose is an Object Data Modeling(ODM) library for MongoDB that helps to manage the application’s data.
General terms of MongoDB
- Database — Can contain one or more collections.
- Collection — Can contain one or more documents.
- Document — Key/Value pair list or array of nested documents.
- Schema — Specific data structure of a document.
- Model — Constructor that takes a specific schema and creates an instance of a document. Models are responsible for creating and reading documents.
Install Mongoose:
npm install mongoose
For connection with mongoose you need to mongodb+srv url by using cloud mongoose(Atlas).
You need to atlas account ( Cluster setup ) to access this mongodb+srv url by click connect button then select Connect with application and copy mongodb+srv url.
Install dotenv:
npm install dotenv
Create config.env file and add your DB url and password:
DB=mongodb+srv://userName:<password>@cluster2.pxessg1q.mongodb.net/?retryWrites=true&w=majority DB_PASSWORD=userpassword
Connect to a MongoDB database add this code in main server.js or index.js:
const mongoose = require("mongoose"); // access env file variables dotenv.config({ path: "./config.env" }); // get mongodb+srv url with password let URL = process.env.DB.replace("<password>", process.env.DB_PASSWORD); mongoose .connect(URL, { useNewUrlParser: true }) .then((cc) => { console.log("DB Connection Successfull"); });
Create a Mongoose userModel file inside model folder:
const validator = require("validator"); const UserSchema = new mongoose.Schema({ name: { type: String, required: true }, email: { type: String, required: [true, "Please provide your email"], unique: true, lowercase: true, validate: [validator.isEmail, "Please provide a valid email"] } }); const User = mongoose.model("User", UserSchema); module.exports = User;
Use Mongoose methods to interact with your database:
const User = require("/models/userModel"); let userData = { name:'myhackinf', email:'myhackinfo@gmail.com' } // create user using userData const userCreate = await User.create(userData); // access user data using find method of mongoose const users = await User.find();
For more info here is mongoose doc url