如何使用Node.js在MongoDB中查找记录

时间:2016-09-19 05:12:03

标签: node.js mongodb express

我正在尝试查找我的收藏集是否有 Button button = (Button) findViewById(R.id.myButton); //set to visible button.setVisibility(View.VISIBLE); //set to invisble button.setVisibility(View.INVISIBLE); //or button.setVisibility(View.GONE); 的记录,如果存在则返回profilename = john如果我返回失败但是在我的情况下,它会在两种情况下都返回成功。我是节点和mongo的新手可以帮助我。

我的功能,

status success

6 个答案:

答案 0 :(得分:1)

如果您只检查是否存在记录,则应该可以使用db.collection.count()方法轻松完成,并检查记录数是否为0。

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

老实说,我是mongodb的新手,我仍然无法理解游标的概念,这是根据https://docs.mongodb.com/manual/reference/method/db.collection.find/

的db.collection.find()的返回类型

答案 1 :(得分:1)

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

答案 2 :(得分:0)

尝试调试。结果的类型是数组,所以尝试检查它的长度:

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

答案 3 :(得分:0)

如果您的query matches表示您拥有record,则返回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);
  });
};

答案 4 :(得分:0)

我认为在您的情况下,req.params.id是一个字符串,例如' 123',但在您的mongodb个人资料名称字段中存储为数字。

所以你可以试试这个:

{profilename:params.id}更改为{profilename:parseInt(params.id)}

答案 5 :(得分:-1)

试试这个

    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)

  });