Mongoose Blank Query查找全部,但特定查询失败

时间:2017-09-02 17:58:48

标签: node.js mongodb mongoose-schema

我正在用express,mongo和mongoose编写一个小型服务器。我的代码:

get value in scope: ['a0'] 
get value in scope: ['a0', 'a1'] 
get value in scope: ['a0', 'a1', 'a2'] 
value: 0

当我尝试使用 const express = require('express'); const MongoClient = require('mongodb').MongoClient const mongoose = require('mongoose'); const COLOURS = ["e6194b", "3cb44b", "ffe119", "0082c8", "f58231", "911eb4", "46f0f0", "d2f53c", "fabebe", "e6beff"]; var url = 'mongodb://localhost:27017/test'; mongoose.connect(url); var app = express(); var db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); db.once('open', function() { console.log('Database connected and open'); }); var deviceSchema = mongoose.Schema({ mac: String, ip: String, colourIndex: Number }); var Device = mongoose.model('Device', deviceSchema); app.get('/register', function (req, res) { console.log("Registration: "); console.log(" MAC: " + req.query.mac); console.log(" IP : " + req.query.ip); Device.find({ mac: /req.query.mac/ }, function(err, deviceList) { if (err || deviceList.length == 0) { console.log(" Cannot find " + req.query.mac + ": " + err); Device.count({ mac: /req.query.mac/ }, function( err, count){ var index = count; console.log("There are " + count + " matching"); var device = new Device({ mac: req.query.mac, ip: req.query.ip, colourIndex: index }); // device.save(function (err, device) { // if (err) { // res.status(500).send("Internal error"); // return console.error(err); // } // res.status(202).send(COLOURS[index]); // }); res.status(202).send(COLOURS[0]); }); } else { console.log(deviceList); res.status(202).send("Success"); console.log(" Colour index: %s", deviceList[0].colourIndex); } }); }); 查找设备时,每次时都会失败。如果我把它留空,它会返回设备(我添加了重复项以检查注释掉的代码)。

我试过看documentationstack overflow

1 个答案:

答案 0 :(得分:1)

/.../表示法不会将变量扩展为其值,因此您字面上搜索字符串req.query.mac(尽管.将匹配任何字符)。

您需要从变量的值创建正则表达式实例,您可以使用RegExp constructor来执行此操作:

Device.find({ mac: new RegExp(req.query.mac) }, ...)

(同样适用于Device.count()

建议使用像escape-string-regexp这样的模块来正确地转义字符串,因为它是外部输入(req.query.mac可能包含在正则表达式模式中具有特殊含义的字符,并且某些模式可能是滥用导致拒绝服务攻击):

const escapeStringRegexp = require('escape-string-regexp');
...
Device.find({ mac: new RegExp(escapeStringRegexp(req.query.mac)) }, ...)