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

我试图find我的集合是否有一个logging与configurationprofilename = john ,如果存在我返回status success ,否则我返回失败,但在我的情况下,它是返回成功的两种情况。我是新来的节点和mongo可以任何一个帮我。

我的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); }); }; 

如果你只是检查一个logging是否存在,你应该很容易的使用db.collection.count()方法来检查logging数是否为0。

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

老实说,我是新的mongodb,我仍然不能理解为根据https://docs.mongodb.com/manual/reference/method/db的db.collection.find()的返回types的游标的想法。 collection.find /

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

尝试debugging。 结果的types是数组,所以尝试检查它的长度:

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

如果你的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); }); }; 

我认为在你的情况下, req.params.id是一个string例如'123',但在你的mongodbconfiguration文件名字段存储为一个数字。

所以你可以试试这个:

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

尝试这个

  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) });