简体   繁体   English

如何搜索mongodb集合条目属性

[英]How to search mongodb collection entry attributes

I have a collection in my mongo database by the name "user collection". 我的mongo数据库中有一个名为“用户集合”的集合。 The collection holds entries with one attribute by the name "DBinstaID". 该集合包含名称为“ DBinstaID”的具有一个属性的条目。

{ "_id" : ObjectId("5595f6be3eaf90ae2d759cc6"), "DBinstaID" : "280430135" }

I am trying to determine whether a new entry has the same DBinstaID value, and if so increase the count of "idCount". 我试图确定一个新条目是否具有相同的DBinstaID值,如果是,则增加“ idCount”的计数。 The following code is used in my index.js routing file for node.js/express. 我的index.js路由文件中的node.js / express使用了以下代码。

var collection = db.get('usercollection');

var checkDuplicate = collection.find({$where: function(){this.DBinstaID === instaID}});

  console.log("DUPLICATE STATUS: " + checkDuplicate);

  if(!(checkDuplicate)){
    idCount++;
  }

However, the checkDuplicate variable is simply set to [object Object] instead of the boolean true or false. 但是,将checkDuplicate变量仅设置为[object Object],而不是布尔值true或false。 How can I search the collection and return a boolean? 如何搜索集合并返回布尔值?

Thank you in advance for the help. 预先感谢您的帮助。

The collection.find() method is asynchronous, this means you can't get the results right away, and you need to handle anything dependant on these results directly in the callback. collection.find()方法是异步的,这意味着您无法立即获得结果,您需要直接在回调中处理任何依赖于这些结果的内容。

I strongly advise you to have a good read of mongoosejs's docs (at least the code examples), and to take a look at basics of asynchronous programming in node.js (a google search away). 我强烈建议您充分阅读mongoosejs的文档 (至少是代码示例),并了解一下node.js中的异步编程基础(谷歌搜索)。

You can use collection.findOne() to get only one result : 您可以使用collection.findOne()仅获得一个结果:

var collection = db.get('usercollection');

collection.findOne({DBinstaID: instaID}, function(err, user) {
    // don't forget to check for errors here, masked for clarity
    console.log("DUPLICATE STATUS: ", user);
    if(user) {
      idCount++;
    }

    // rest of the code
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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