Skip to main content

Model

What is a model

  • Models are constructors compiled from Schema definitions
  • Models are responsible for creating and reading documents from the underlying MongoDB database
  • An instance of a model is called a document

Create a Schema first

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/mydb')
.then(()=>console.log('Connected to MongoDB...');)
.catch(err=>console.log('Failed to connect MongoDB...',error));

const courseSchema = new mongoose.Schema({
new:String,
author:String,
tags:[String],
date{type:Date,default:Date.now},
isPublished:Boolean,
price:Number
});

Create a model

  • The first argument is the singular name of the collection your model is for
  • Mongoose automatically looks for the plural, lowercased version of your model name
const Course = mongoose.model('course',courseSchema);

Create an instance of the model

const course = new Course({
name:'NodeJS Course',
author:'James',
tags:['node','backend'],
isPublished:true
});

Save document to database

const createCourse=async()=>{
const course = new Course({
name:'NodeJS Course',
author:'James',
tags:['node','backend'],
isPublished:true
});
const result = await course.save();
console.log(result);
}
createCourse();