【问题标题】:$regex requires regular expression error mongodb stitch$regex 需要正则表达式错误 mongodb 缝合
【发布时间】:2018-04-04 11:56:56
【问题描述】:

当我尝试查询 Mongodb Stitch 时出现此错误:

错误:$regex 需要正则表达式 在 client.js:557

这是我的代码:

const searchByName = async (data) => {
    let db = await MongoConnect(),
      collection_users = db.collection('users'),
      users

console.log(data.name)

let regxName = new RegExp(data.name)

console.log(regxName)

try {
    let users = await collection_users.find({ name: { $regex: regxName, 
      $options: 'i' } }).execute()
    console.log(users)
} catch (error) {
    return error
}

【问题讨论】:

  • 调试并找出regxName填充的值。
  • console.log(data.name) 产生什么?

标签: javascript regex mongodb mongodb-stitch


【解决方案1】:

感谢您的帮助,此方法有效。 (所有客户端)

import { BSON } from 'mongodb-stitch'

let bsonRegex = new BSON.BSONRegExp('pattern', 'i')

let users = await collection_users.find({ name: bsonRegex }).execute()

从模式返回结果

【讨论】:

  • 谢谢!常规 RegExp 在控制台中工作时在 Stitch 中不起作用,但 BSON 解决了​​这个问题。
【解决方案2】:

在 MongoDB Stitch Functions 中,您必须使用 BSON.BSONRegExp 全局函数将其转换为 Stitch 的正确格式。

这是一个例子:

exports = function(keyword) {
    var mongodb = context.services.get("mongodb-atlas");
    var coll = mongodb.db("DBNAME").collection("users");
    return coll.find({
      name: BSON.BSONRegExp(keyword, "i") 
    }).toArray();
};

并在客户端上调用它:

stitchClientPromise.then(stitchClient => 
  stitchClient.executeFunction('FUNC_NAME', 'jhon')
).then(users => console.log('success: ', users))
  .catch(e => console.log('error: ', e));

【讨论】:

    猜你喜欢
    • 2018-07-14
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多