我使用Node-RED为MongoDB创建了一个小型REST-API。
这很好用:<node-red-url>:<node-red-port>/rest/demo
向我显示所有条目。
我甚至可以过滤结果:追加?userName=demo
仅显示{userName: "demo"}
的条目。
在我的数据库中,我有一些数字值。像{weight: 10}
这样的东西。请注意,这不是{weight: "10"}
!
现在我只想要{weight: 10}
的条目。但是当我追加?weight=10
时,转移的参数会将10
转换为"10"
。其中没有命中,因为我的所有weight
- 值都是数字而不是字符串。
我可以以某种方式更改附录以按weight
过滤吗?或者我是否必须优化我的REST逻辑?
//编辑: 这就是我的流程:
[{"id":"c4a27b53.59303","type":"mongodb in","z":"99225255.0516b8","mongodb":"7e071505.7198bc","name":"","collection":"demo","operation":"find","x":660,"y":580,"wires":[["852d2853.264698"]]},{"id":"af5a916a.08366","type":"function","z":"99225255.0516b8","name":"parseQuery","func":"msg.payload = (msg.req.query);\n\nmsg.limit = 100;\nmsg.skip = 0;\n\nreturn msg;","outputs":1,"noerr":0,"x":330,"y":580,"wires":[["c4a27b53.59303"]]},{"id":"6b0b1b4b.eb8b2c","type":"http in","z":"99225255.0516b8","name":"","url":"/rest/demo","method":"get","swaggerDoc":"","x":120,"y":580,"wires":[["af5a916a.08366"]]},{"id":"852d2853.264698","type":"http response","z":"99225255.0516b8","name":"","x":950,"y":580,"wires":[]},{"id":"7e071505.7198bc","type":"mongodb","z":"","hostname":"192.168.100.166","port":"27017","db":"training","name":"debianTraining"}]
// EDIT2: 的更新
我用更多服务器逻辑修复了这个问题:
if (msg.payload.hasOwnProperty('weight')) {
msg.payload.weight = parseInt(msg.payload.weight);
}
我添加了两个案例来搜索&#34;大于&#34;和&#34;小于&#34;:
if (msg.payload.hasOwnProperty('weightG')) {
msg.payload = {"weight": {$gt: parseInt(msg.payload.weightG)}};
delete msg.payload['weightG'];
}
if (msg.payload.hasOwnProperty('weightL')) {
msg.payload = {"weight": {$lt: parseInt(msg.payload.weightL)}};
delete msg.payload['weightL'];
}
到目前为止一切正常。
答案 0 :(得分:1)
好的,看过将HTTP查询转换为Mongo查询的函数节点,我认为没有一种很好的方法可以动态地为Mongo中的任意对象执行此操作。
所有HTTP查询参数都将成为字符串,因此如果您知道文档中的某个特定字段是一个数字,那么您只能转换该字段。 e.g。
msg.payload = (msg.req.query);
if (msg.payload.hasOwnProperty('weight')) {
msg.payload.weight = parseInt(msg.payload.weight)
}
msg.limit = 100;
msg.skip = 0;
return msg;