简体   繁体   中英

How to find a record in MongoDB using Node.js

I am trying to find whether my collection has a record with profilename = john and if exists I return status success if else I return fail but in my case, it is returning success for both cases.I am new to node and mongo can any one help me.

My function,

    exports.searchprofilename = function (req, res) {
  var params = req.params;console.log(req.params.id);
  var record= db.collection('profile');
   record.find({profilename:params.id}, (err, result) => {
   if (err){ return console.log(err)
    }
      if(!result){
            data = {status:'success'};
        } else{
             data = {status:'profile name already exists'};
        }
      res.send(data);
  });
};

If you are only checking if a record exists, you should be easily able to do it using db.collection.count() method and checking if the number of records = 0 or not.

https://docs.mongodb.com/manual/reference/method/db.collection.count/

Honestly, I am way new to mongodb and I still cannot grasp the idea of cursors which is the return type of db.collection.find() as per https://docs.mongodb.com/manual/reference/method/db.collection.find/

我通过将find({})更改为findOne({})来清除它,谢谢大家。

If your query matches then it means you have record then return Success

 exports.searchprofilename = function (req, res) {
  var params = req.params;console.log(req.params.id);
  var record= db.collection('profile');
   record.find({profilename:params.id}, (err, result) => {
   if (err){ return console.log(err)
    }
    // If record exist then return 'Success'
      if(result.length>0){
            data = {status:'success'};
        } else{
             data = {status:'profile name already exists'};
        }
      res.send(data);
  });
};

Try this

    exports.searchprofilename = function (req, res) {
        console.log("PARAMS",req.params.id);
        var data = {};
        profile.findOne( {profilename:req.params.id} , function (err, fetchDataObj) {
                if (err) {
                    console.log(err)
                   return err;
                } else {
                    data.status = 'success';
                    data.result = fetchDataObj;
                    return data;
                }
            }).lean(true)

  });

I think in your case, req.params.id is a String for example '123', but in your mongodb profilename field is stored as an Number.

So you can try this:

change {profilename:params.id} to {profilename:parseInt(params.id)}

Try to Debug. the type of result is array, so try to check the length of it:

if(result.length==0){
    data = {status:'success'};
} else{
    data = {status:'profile name already exists'};
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM