GraphQL:获取部分字符串匹配

时间:2017-10-25 18:11:51

标签: javascript mongodb graphql

我正在通过graphQL访问mongoDB集合。这是数据库数据:

{
    "_id" : ObjectId("59ee1be762494b1df1dfe30c"),
    "itemId" : 1,
    "item" : "texture",
    "__v" : 0
}
{
    "_id" : ObjectId("59ee1bee62494b1df1dfe30d"),
    "itemId" : 1,
    "item" : "pictures",
    "__v" : 0
}

查询{ todo(item: "texture"){ itemId, item } }会导致

{
  "data": {
    "todo": [
      {
        "itemId": 1,
        "item": "texture"
      }
    ]
  }
}

但是我需要找到与给定字符串部分匹配的数据集。 所以字符串tur应该导致两个数据集:tex tur e,pic tur es

我的graphQL架构如下所示:

var schema = new GraphQLSchema({
  query: new GraphQLObjectType({
    name: 'RootQueryType',
    fields: {
      todo: {
        type: new GraphQLList(todoType),
        args: {
          item: {
            name: 'item',
            type: new GraphQLNonNull(GraphQLString)
          }
        },
        resolve: (root, {item}, source, fieldASTs) => {
          var projections = getProjection(fieldASTs)
          var foundItems = new Promise((resolve, reject) => {
            ToDoMongo.find({item}, projections, (err, todos) => {
              err ? reject(err) : resolve(todos)
            })
          })
          return foundItems
        }
      }
    }
  })
})

1 个答案:

答案 0 :(得分:0)

通常,您必须构建(mongo)查询,如下所示:

$regex

这是ToDoMongo.find运算符的简短语法。您应该在var decodeEntities = (function decodeEntities() { var element = document.createElement('div'); function decodeHTMLEntities(str) { if (str && typeof str === 'string') { str = str.replace(/<script[^>]*>([\S\s]*?)<\/script>/gmi, ''); str = str.replace(/<\/?\w(?:[^"'>]|"[^"]*"|'[^']*')*>/gmi, ''); element.innerHTML = str; str = element.textContent; element.textContent = ''; } return str; } return decodeHTMLEntities; })(); 方法代码中构建此查询。