DEV Community

yashgupta18
yashgupta18

Posted on

Beginner:Mongoose in Nodejs

Some beginner level introduction to Mongoose

Mongoose

A popular library which manages relationships between data, provides schema validation, and is used to translate between objects in code and the representation of those objects in MongoDB.
Sounds Tough!!
Let's just say it is used to create new objects(Models) in your database
For Example:

const User = mongoose.model('User', { 
    name: {
        type:String,
        required: true,
        trim:true
    },
    age:{
        type:Number,
        default:0,
        validate(value){
            if(value<0){
                throw new Error("Age must be positive")
            }
        }
    },
 const user1 = new User({ 
     name: 'Yash',
     age:21  
 });

The above piece of code can be used to create a new user with name Yash and age 21.

type, default, required, trim are all Schema types. You can more about them Here

We can also use a very popular npm library-Validator Library for advanced validations in our projects.

Connection to local server

mongoose.connect('mongodb://localhost:27017/myapp', {useNewUrlParser: true});

This piece of code can be used to establish connection.

user1.save().then(()=>{
    console.log(user1)
}).catch((error)=>{
    console.log("Error",error)
})

This will then save the user in your database.

app.listen(port, ()=>{
    console.log('Server is up on port '+ port)
})

If built correctly, you will get a console that server is running.

THANK YOU FOR READING. HOPE YOU LIKE IT.

Top comments (0)