Skip to content

Instantly share code, notes, and snippets.

@dineshdeveloper1
Last active November 3, 2023 04:31
Show Gist options
  • Save dineshdeveloper1/13d3748927beb09a54d08e402ba8dcee to your computer and use it in GitHub Desktop.
Save dineshdeveloper1/13d3748927beb09a54d08e402ba8dcee to your computer and use it in GitHub Desktop.
Connect MongoDB with Node.js Using Mongoose
//installation process
npm init -y
npm install mongoose
npm install express
npm i --save-dev nodemon - package.json - scripts - “start”:”nodemon index.js”
create a file - index.js
//step 1
const express = require('express');
const app = express()
app.listen(8080, ()=>{
console.log("Server is running on port 8080");
})
//(if mongodb not connected, go to task manager > mongodb > restart/start)
//Connect MongoDB with Node.js Using Mongoose
const express = require('express');
const mongoose = require('mongoose');
const app = express()
mongoose.connect('mongodb://127.0.0.1:27017/amazon-database')
const UserSchema = new mongoose.Schema({ //database schema refers to the logical and visual configuration of the entire relational database.
name: String,
price: Number
})
const UserModal = mongoose.model('products', UserSchema)
app.get('/products', (req, res) => {
UserModal.find({}).then(function (users) {
res.json(users)
}).catch(function (err) {
console.log('error found', err)
})
})
app.listen(8080, () => {
console.log("Server is running on port 8080");
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment