Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to write basic query(find and findById) using node.js and mongoDb?

    • 1
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 748
    Comment on it

    As in my previous chapter I have explained how we will authenticate using passport module. Now I will explain that how we will write basic query using node.js and mongoDb.

    Here are the few query which I will implement step by step:

     

    Step 1: First we will create routes.

    var loginController       = require('../controller/loginController');
    
    app.get('/userList', loginController.userList); 

     

    Here we can see that above we have defined the controller as a object then we are using the method userList of loginController object.

     

    Step 2: Now we will go to the controller loginController and use userList method.

    var userModel       = require('../app/models/user');
    
    module.exports.userList = function(request, response,next){
        userModel.find({
             deleted: 'false'
        }, function(err, usersList){
            if(err){
                res.json(err);
            }
            else {
                
                console.log('users== ' + usersList)
                res.render('user_list', {
                    title : 'List of users',
                    user_data : usersList
                });
            }
        });
    };

    Here we can see that in above we can define the user model and for getting user list we are using find query and that query will return an array of user.

    Similarly, we also find an individual user by using findById query. Here is the example of findById.

     

    User.findById(friend.friend.anotherfriendid, function(err, user) {
    	//write any code in else section which you want
    });

     

    Here we can see that we found a single user and then we have passed a callback and on the success of that function we will carry on the further code which we want to write .

    Here is the basic flow which we will follow while writing the query in node.js and mongoDb.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: