An Interest In:
Web News this Week
- April 27, 2024
- April 26, 2024
- April 25, 2024
- April 24, 2024
- April 23, 2024
- April 22, 2024
- April 21, 2024
April 15, 2022 06:42 am GMT
Original Link: https://dev.to/sujon554/setup-mongodb-in-nodejs-with-mongoose-4229
Setup MongoDB in Node.js with Mongoose
Setting up database connection
npm install mongoose --save
First let import the dependency;
const mongoose = require("mongoose");
Then lets store the path of the database in a variable. The path should look like the following, with and being replaced with a user you have created for the database.
const dbPath = "mongodb://<dbuser>:<dbpassword>@ds250607.mlab.com:38485/test-db";
connect to the database.
mongoose.connect(dbPath, { useNewUrlParser: true,});
module.exports = mongoose;
Once the application is started, it would be better if there was an indicator showing whether the application successfully connected to the database or not. So lets add some more code to fix that.
const db = mongoose.connection;db.on("error", () => { console.log("> error occurred from the database");});db.once("open", () => { console.log("> successfully opened the database");});
In the end the database.js should look like this.
// database.jsconst mongoose = require("mongoose");const dbPath = "mongodb://<dbuser>:<dbpassword>@ds250607.mlab.com:38485/test-db";mongoose.connect(dbPath, { useNewUrlParser: true,});const db = mongoose.connection;db.on("error", () => { console.log("> error occurred from the database");});db.once("open", () => { console.log("> successfully opened the database");});module.exports = mongoose;
Setting up models/schema
// models/userModel.jsconst mongoose = require("../database");const schema = { name: { type: mongoose.SchemaTypes.String, required: true }, email: { type: mongoose.SchemaTypes.String, required: true }, password: { type: mongoose.SchemaTypes.String, required: true, select: false }};const collectionName = "user"; // Name of the collection of documentsconst userSchema = mongoose.Schema(schema);const User = mongoose.model(collectionName, userSchema);module.exports = User;
// Create userUser.create({ name: name, email: email, password: password});// Find user by emailUser.findOne({ email: email});// Find user by email with the password field includedUser.findOne({ email: email}).select("+password");
Original Link: https://dev.to/sujon554/setup-mongodb-in-nodejs-with-mongoose-4229
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To