【问题标题】:Why "where" of mongodb is not working in node.js?为什么 mongodb 的“哪里”在 node.js 中不起作用?
【发布时间】:2018-03-29 21:59:39
【问题描述】:

我是node.jsmongodb 的完整初学者,所以如果我的问题看起来很愚蠢,请原谅。基本上我正在尝试使用whereor 运算符执行以下操作从this question 得到一些精炼的结果,但它显示错误。

代码:

//here "data" is the emitted socket object from client side
var string = data.search.replace(/[\/\\#@+()$~%'":*?<>{}]/g, '')
        var regex = new RegExp(["^", string].join(""), "i");
        db.collection("user_information").find()
        .where('_id').ne(data.userId)
        .or([
           {email: regex}, 
           {fullname:regex}
         ])
        .select('fullname email')
        .exec(function(err, res){
         console.log(res)
        })

错误:

TypeError: db.collection(...).find(...).where is not a function
at C:\chat\mongo.js:1898:14
at connectCallback (C:\Users\Srinu\AppData\Roaming\npm\node_modules\mongodb\lib\mongo_client.js:515:5)
at C:\Users\Srinu\AppData\Roaming\npm\node_modules\mongodb\lib\mongo_client.js:430:11
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)

【问题讨论】:

    标签: node.js mongodb


    【解决方案1】:

    您链接到的问题与 Mongoose ORM library 的使用有关,而不是 Node.js 的标准 MongoDB 驱动程序。前者建立在后者之上,并公开了更高级别的 API。如果您想使用其他问题中的代码,则需要安装并导入 Mongoose。

    或者,如果您想继续单独使用 Node 驱动程序,您可以通过传递 query object 作为 find 的第一个参数来执行查询 - 例如,您的第一个“位置”看起来像这个:

    db.collection("user_information").find({
        _id: { $ne: data.userId }
    })
    

    我建议您阅读 MongoDB itselfNode driver 的文档以了解更多信息。

    【讨论】:

    • 非常感谢您救了我的一天
    猜你喜欢
    • 1970-01-01
    • 2014-08-20
    • 1970-01-01
    • 2017-11-06
    • 2022-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多