无法将参数传递给mongo find集合

Not able to pass parameter to mongo find collection

本文关键字:mongo find 集合 参数传递      更新时间:2023-09-26

Req.params在db.collection.find执行后获取值。有人能告诉我这个代码做错了什么吗?

exports.findAll = function(req, res) {
    var postal = parseInt(req.params.postal);
    db.collection('ifscdata', function(err, collection) {
        collection.find({'ADDRESS':/postal/}).toArray(function(err, items) {
            res.send(items);
        });
    });

我应该根据邮寄地址进行部分搜索。但我无法将价值传递给邮政,因为它只有在之后才能获得价值。

功能路线是这个

app.get('/ifsc/:postal', ifsc.findAll);

示例URL:

http://localhost:3000/ifsc/691009

看起来您需要在查询中使用regex,请考虑使用RegExp对象包装变量,如下所示:

exports.findAll = function(req, res) {
    var postal = req.params.postal, 
        regex = new RegExp(postal);
    db.collection('ifscdata', function(err, collection) {
        collection.find({'ADDRESS': regex}).toArray(function(err, items) {
            res.send(items);
        });
    });

为什么在postal之间加斜线?

你试过这个吗?

exports.findAll = function(req, res) {
    var postal = parseInt(req.params.postal);
    db.collection('ifscdata', function(err, collection) {
        collection.find({'ADDRESS': postal}).toArray(function(err, items) {
            res.send(items);
        });
    });