查询Mongo数据库

我需要对我的mongo数据库中的以下条目执行查询:

{ "_id" : ObjectId("597b19512a5b1c3258e6440e"), "fdata" : [ { "type" : "header", "subtype" : "h1", "label" : "Date Of Commencement" }, { "type" : "paragraph", "subtype" : "p", "label" : "The partnership business shall be deemed to have commenced on and from :" }, { "type" : "date", "label" : "Date Field", "description" : "Enter correct date as per instructions in the clause", "className" : "form-control", "name" : "date-1501239537753" }, { "type" : "button", "subtype" : "submit", "label" : "Next", "className" : "btn btn-primary", "name" : "button-1501239595350", "style" : "primary" } ] } 

我必须获取整个名为fdata的数组,我可以使用的参数是名为cl的数组中的label的值,如下所示:

 cl = ['Date Of Commencement']; 

我的问题是如何访问该数组条目,因为下面的代码给了我一个“意外的令牌”

我的查询是这样的:(在后端使用NodeJS)

  for(var i=0; i<cl.length ;i++) { var dummy = cl[i]; //console.log(dummy); result[i] = db.collection('clauses').findOne({fdata[0].label: dummy},{fdata}); } 

它在一个循环中,因为在大多数情况下,数组cl将有多个条目。

您使用的findOne查询是asynchronous的。 这就是为什么你看到[ Promise { <pending> } ] 。 有很多方法来处理asynchronous行为:

  • callback
  • asynchronous库
  • 承诺
  • 发电机+协同程序
  • asynchronous+等待

如果你的Nodejs版本足够新(8+),它应该支持asynchronous/等待的方法。

 async function doJob(arr) { const clauses = db.collection('clauses'); for (const key of arr) { const result = await clauses.findOne({'fdata.label': key}); console.log(result); } }