- Open account on mongodb atlas
- Create cluster
- Create collection
- Set up connection
- Set up and get dbURI
Setting up connection in app.js
const dbURI = 'mongodb+srv://yourusername:yourpassword@nodetuts.3g4hc.mongodb.net/yourdatabasename?retryWrites=true&w=majority';
mongoose.connect(dbURI)
.then(result=> app.listen(3000))
.catch(err=> console.log('some error occurred'))
.then(result=>app.listen(3000))
means after the database connection is made then app will start listening to the requests.
Setting up model
Create a file called 'blog.js' inside a folder '/models'.
Then in blog.js:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const blogSchema = new Schema({
title:{
type: String,
required: true
},
snippet: {
type: String,
required: true
},
body:{
type: String,
required: true
}
}, { timestamps: true });
const Blog = mongoose.model('Blog', blogSchema);
module.exports = Blog;
We will create a model and the model will be built on a schema.
Creating a schema: const Schema = mongoose.Schema
and const blogSchema = new Schema({})
const Blog = mongoose.model('Blog', blogSchema);
The second 'Blog' name is important. Mongoose will pluralize this and search a model of that name, i.e. 'Blogs' in server.
Getting and Saving Data
We can insert by the following way using .save()
method.
app.get('/add-blog', (req, res) => {
const blog = Blog({
title: 'Blog Post 1',
snippet: 'you can also drag a cover image',
body: 'MongoDB provides high availability with replica sets'
});
blog.save()
.then( result => res.send(result))
.catch(err => console.log(err));
})
We can retrive all the data by following way using .find()
method
Blog.find()
.then( results => res.send(results))
.catch( err => console.log(err))
We can retrieve single data by the following way using .fingById()
method:
app.get('/single-blog', (req, res) => {
Blog.findById('5fa27e3d1ca6c8027cc7497b')
.then( result => res.send(result))
.catch( err => console.log(err))
})
Also we can sort the data:
Blog.find().sort({ createdAt: -1 })
.then( results => res.send(results) )
.catch( err => console.log(err) )
-1
means descending order.
Top comments (0)