Sunday, May 23, 2021

Connecting to mongodb using mongoose,creating a schema,model and saving the object to mongodb as document

 To install mongoose.


npm i mongoose


We will create below all codes in index.js for demo and run it using: node index.js


To connect mongodb:


connect mongoose = require("mongoose");

mongoose.connect('mongodb://localhost/playground')
 .then(()=>console.log('Connected to MongoDB...'))
 .catch(err=>console.error('Could not connect to MongoDB...',err))

create a schema to design a shape of document of collection in MongoDB.
collection == table, document == row.
const courseSchema = new mongoose.Schema({
  name: String,
  author: String,
  tags: [ String ],
  date: {
    type: Date,
    default: Date.now
  },
  isPublished: Boolean
});

Schema Types supported: String,Number,Date,Buffer,Boolean,ObjectID,Array
To compile Schema to a Model.It is a blueprint for document in MongoDB, which is created by compiling the Schema.
const Course = mongoose.model('Course',courseSchema);//singular name of collection is given as first argument

using the Model to create an object which we will save as document.
const course = new Course({
 name: 'Node js course',
 author: 'Mosh',
 tags: ['node','backend'],
 isPublished: true
});

saving the object created from Model as a document in mongodb.
const result = await course.save();
console.log(result);

When we use await, it should be in async function.
async function createCourse(){
 const course = new Course({
 name: 'Node js course',
 author: 'Mosh',
 tags: ['node','backend'],
 isPublished: true
});
const result = await course.save();
console.log(result);
}
createCourse();

No comments:

Post a Comment