xxxxxxxxxx
const mongoose = require('mongoose');
const connectDB = async () => {
mongoose
.connect('mongodb://localhost:27017/playground', {
useCreateIndex: true,
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false
})
.then(() => console.log('Connected Successfully'))
.catch((err) => console.error('Not Connected'));
}
module.exports = connectDB;
xxxxxxxxxx
import mongoose from 'mongoose'
export const connectDb = async () => {
try {
await mongoose.connect('mongodb://localhost:27017/test', {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
})
} catch (error) {
console.log(error.message)
}
}
xxxxxxxxxx
//Import the mongoose module
var mongoose = require('mongoose');
//Set up default mongoose connection
var mongoDB = 'mongodb://127.0.0.1/my_database';
mongoose.connect(mongoDB, {useNewUrlParser: true, useUnifiedTopology: true});
//Get the default connection
var db = mongoose.connection;
//Bind connection to error event (to get notification of connection errors)
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
xxxxxxxxxx
const mongoose = require("mongoose");
// database connection with mongoose
mongoose.connect("mongodb://localhost/todos", {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => console.log("connection successful"))
.catch((err) => console.log(err));
xxxxxxxxxx
//Es6
import mongoose, { connect } from "mongoose";
//import dotenv from "dotenv";
// dotenv.config({ silent: process.env.NODE_ENV === 'production' });
export const connectDB = async () => {
try {
mongoose.set('strictQuery', true) //only use this mongoose.set()to suppress this warning
//await mongoose.connect(process.env.MONGODB_URI, { dbname: process.env.DB_NAME }, { //env file connect method
await mongoose.connect('mongodb://localhost:27017/testDB', { //normal db connect method
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => {
console.log("mongodb connected..");
})
} catch (error) {
console.log(error.message);
}
}
xxxxxxxxxx
const express = require('express');
const app = express();
const path = require('path');
const mongoose = require('mongoose');
const PORT = process.env.PORT || 3000;
mongoose.set('strictQuery', false);
mongoose.connect('mongodb+srv://sajidrec:password@testdb.zazbcdw.mongodb.net/testdb', {
useNewUrlParser: true,
useUnifiedTopology: true,
}
).then().catch((err) => { console.log('database connection error', err) });
app.use(express.urlencoded({ extended: false }));
const userShema = new mongoose.Schema({
name: { type: String },
email: { type: String },
pass: { type: String }
});
const usrModel = mongoose.model('user', userShema);
app.route('/')
.get((req, res) => {
res.sendFile(path.join(__dirname, 'index.html'));
});
app.route('/pst')
.post(async (req, res) => {
await new usrModel({
name: req.body.name,
email: req.body.email,
pass: req.body.pass
}).save();
res.sendFile(path.join(__dirname, 'done.html'));
});
app.listen(PORT, () => {
console.log(`server running at port ${PORT}`);
});
xxxxxxxxxx
// local conecation
const mongoose = require("mongoose");
mongoose
.connect("mongodb://localhost:27017/testdb")
.then(() => console.log("Connected to MongoDB..."))
.catch((err) => console.error("Could not connect to MongoDB...", err));
xxxxxxxxxx
- In your entry file
mongoose
.connect("mongodb://localhost/vidly")
.then(() => console.log("Connected to MongoDB..."))
.catch((err) => console.log("Cloud not connect to MongoDB..."));
xxxxxxxxxx
//config/db.js
const mongoose = require('mongoose');
const connect = async () => {
try {
await mongoose.connect(process.env.MONGODB);
console.log('database connect');
} catch (error) {
console.log(error.message);
}
};
module.exports = connect;
//index.js
require('dotenv').config();
const connect = require('./config/db');
connect();
xxxxxxxxxx
const mongoose = require('mongoose');
// Database connection
mongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
});
// User model
const User = mongoose.model('User', {
name: { type: String },
age: { type: Number }
});
// Only one parameter [query/condition]
// Find all documents that matches the
// condition name='Punit'
User.find({ name: 'Punit'}, function (err, docs) {
if (err){
console.log(err);
}
else{
console.log("First function call : ", docs);
}
});
// Only Two parameters [condition, query projection]
// Here age:0 means don't include age field in result
User.find({ name: 'Punit'}, {age:0}, function (err, docs) {
if (err){
console.log(err);
}
else{
console.log("Second function call : ", docs);
}
});
// All three parameter [condition, query projection,
// general query options]
// Fetch first two records whose age >= 10
// Second parameter is null i.e. no projections
// Third parameter is limit:2 i.e. fetch
// only first 2 records
User.find({ age: {$gte:10}}, null, {limit:2}, function (err, docs) {
if (err){
console.log(err);
}
else{
console.log("Third function call : ", docs);
}
});