How to create document using mongoose in express-node app


Mongoose is MongoDB driver module which provide REST features to build faster MongoDB apps with Nodejs.

MongoDB

MongoDB is a NoSQL database which store data as JSON document and collections. In JavaScript applications we can utilize the mongoose driver to perform Mongo operations. First up all we need to install mongoose to your project and then import the module.

npm install mongoose

Saving the document

mongoose uses the modal class to perform REST operations. If you are not familiar have a look at the mongoose modal post given below

Tag.create({
tagName: tagNa}, function(error, stag) {
if (error) return handleError(error)
 console.log(new tag saved : ${stag.tagName});
})

The Tag is the Modal and the create method is used to save the document to database and it also use a callback function to return the result.

We can also use an asynchronous method find documents in Mongoose as follows

const tag=new Tag({tagName:'SQL'})
await tag.save()

That’s it. Following mongoose posts deserve your attention

How to create Modal for CURD using Mongoose in express-node app


Mongoose is MongoDB driver module which provide REST features to build faster MongoDB apps with Nodejs.

Modal

Mongoose allow us to perform CURD operation using REST full Modals. A Modal is basically is an object/class which define all fields with validation and also connected to your MongoDB.

To perform operation ,create variables of the modal and call the save/ create method. Following is a sample Modal class

const mongoose = require('mongoose');
 const UserSchema = new mongoose.Schema({
     name :{
         type:String,
         required: '{PATH} is required!'
     },
     bio: {
         type:String
     },
     email:{
         type:String
     },
     website:{
         type:String
     },
     password:{type:String,required: '{PATH} is required!',default:"123"},
 posts : [     {type: mongoose.Schema.Types.ObjectId,ref:'Post'} ]
 },{
     timestamps: true
 })
 module.exports = mongoose.model('User',UserSchema);

In the modal class you can store another document using ObjectID .Here is an example for the create document using the modal class

const user = await User.create({
             name,
             email,
             bio,
             website
         })

That’s it. Following mongoose posts deserve your attention

How to find document byId using mongoose in express-node app


Mongoose is MongoDB driver module which provide REST features to build faster MongoDB apps with Nodejs.

Mongo Object Id

MongoDB object ID is an automatically generated multipurpose number. In our case we can use it to show up the document. In fact the Object ID consist of date and a unique random number.

Find records using MongoDB ObjectId

  Post.findById(pid,function (error, post) {
       if (error) return handleError(error)
          if (post) {
               console.log("Full post :" + post);
          }
        });  

Using the findById method of mongoose model class allows us to find the document using MongoDB object Id and return result to the call back function in JavaScript style.

We can also use an asynchronous method find documents in Mongoose as follows

const post=await Post.findById(id)

and the resulted document will be

That’s it. Following mongoose posts deserve your attention

How to place list of objects in MongoDB-Express app


With mongoose we can easily place list of objects and populate documents/objects in MongoDB.

The Modal objects

In the modal object of Post we can define a field for user which is another modal in our project.

The User Schema and ‘post’ list field

const mongoose = require('mongoose');
 const UserSchema = new mongoose.Schema({
     name :{
         type:String,
         required: '{PATH} is required!'
     }, 
     posts : [
         {type: mongoose.Schema.Types.ObjectId,ref:'Post'}
     ]    
 ,{
     timestamps: true
 })
 module.exports = mongoose.model('User',UserSchema);

The Post Schema

const mongoose = require('mongoose');
 const PostSchema = new mongoose.Schema({
     title: {
         type: String,
         required:   '{PATH} is required!'
     },
     content: {
         type: String,
         required:   '{PATH} is required!'
     },
 }, {
     timestamps: true
 })
 module.exports = mongoose.model('Post', PostSchema);

In the user we had defined a field posts (list ), which is intended to store the user posts object ( MongoDB object ID), which can be used for populating the post later.

In the express route method we have the postsByUser which fetch the user post in the user documents

 postsByUser: async (req, res) => {
        try {
           const {  id  } = req.params;
        console.log('User:'+id);
        const user = await User.findById(id).populate('posts');
        console.log('User ->' + user);
        res.send(user.posts);
         } catch(e) {
             // statements
             console.log(e);
             res.sta(401).send({error:e})
         } 
    }

The the route is called in the following manner

http://localhost:3005/user/find/post/5fe4ab1e69b8d525c44ec293

and the user posts will be shown as following

{
      "posts": [
        {
            "comments": [],
            "tags": [],
            "_id": "5fedcb477563625708ca7429",
            "title": "Welcome to react",
            "content": "A hello world Reactjs app",
            "user": "5fe4ab1e69b8d525c44ec293",
            "createdAt": "2020-12-31T12:59:51.559Z",
            "updatedAt": "2020-12-31T12:59:51.559Z",
            "__v": 0
        },
        {
            "comments": [],
            "tags": [],
            "_id": "5fedcbe67563625708ca742a",
            "title": "Helo",
            "content": "Hello word app",
            "user": "5fe4ab1e69b8d525c44ec293",
            "createdAt": "2020-12-31T13:02:30.724Z",
            "updatedAt": "2020-12-31T13:02:30.724Z",
            "__v": 0
        },   
}          

That’s it. Following mongoose posts deserve your attention

Use Object id to set relationship in MongoDB-Express app


Unlike relational database NoSql (MongoDB) don’t have relation between documents. Even though we can set relation by placing sub document inside one document using the Object id, which is generated by the MongoDB.

The Modal objects

In the modal object of Post we can define a field for user which is another modal in our project.

Continue reading Use Object id to set relationship in MongoDB-Express app

How to display MongoDB Object using the Mongoose in MongoDB-Express app


Mongoose is MongoDB driver module which provide REST features to build faster MongoDB apps with Nodejs.

Mongo Object Id

MongoDB object ID is an automatically generated multipurpose number. In our case we can use it to show up the document. In fact the Object ID consist of date and a unique random number.

The mongoose schema

const mongoose = require('mongoose');
 const PostSchema = new mongoose.Schema({
     title: {
         type: String,
         required:   '{PATH} is required!'
     },
     content: {
         type: String,
         required:   '{PATH} is required!'
     },
  user: {     type: mongoose.Schema.Types.ObjectId,     ref: 'User' }
 }, {
     timestamps: true
 })
 module.exports = mongoose.model('Post', PostSchema);

Here the user field is an example for the Object ID field and the resulted document will look like the following

New Post:{                                                                                                                      
   _id: 5fee99c33cbe8b25d0ced080,                                                                                                
   title: 'Happy New Year',                                                                                                      
   content: 'Happy New Year MEssage',                                                                                            
   user: 5fe4ab1e69b8d525c44ec293,                                                                                               
   createdAt: 2021-01-01T03:40:51.340Z,                                                                                          
   updatedAt: 2021-01-01T03:40:51.340Z,                                                                                          
   __v: 0                                                                                                                        
 }                

Populate the user

Using the populate command we can get the complete User information which will be show as sub document/sub object. To populate the result we have to use the populate ,exec and create a caller function

Post.findById(post._id).populate('user').exec(function(error, post) {
                 console.log('New post - > ' + post);
             })

and the resulted document will be

New post - > {         
        "_id": "5fe6ca78443a4d0f54aafecf",
        "title": "Hosting",
        "content": "4 Month free hosting plans for 100 developer opens now",
        "user": {   
            "_id": "5fe4db85a4896d069006601b",
            "name": "emma",
            "createdAt": "2020-12-24T18:18:45.224Z",
            "updatedAt": "2020-12-24T18:20:47.857Z",
            "__v": 1
        },
        "createdAt": "2020-12-26T05:30:32.715Z",
        "updatedAt": "2020-12-26T05:30:32.715Z",
        "__v": 0
    }

That’s it. Following mongoose posts deserve your attention