【问题标题】:Node js REST Service mongodb distinct array emptyNode js REST Service mongodb distinct 数组为空
【发布时间】:2018-09-09 15:10:45
【问题描述】:

我是一名初级开发人员,我正在使用 Azure 上的 Node JS、Express、MongoDB 开发一个 REST 服务。 在我的数据库上,我有一个带有模型、类型等字段的更多机器的集合,当我执行不同的查询时,我收到一个字符串数组作为响应。 示例:

[
"Massey Ferguson",
"JOHN DEERE",
"FENDT",
"NEW HOLLAND",
"CASE-IH",
"DEUTZ-FAHR",
"VALTRA/VALMET",
"SAME",
"BCMH",
"CASE",
"CATERPILLAR",
"CHALLENGER"
]

现在我已经编写了一个 GET 服务:

router.get('/machine_brand', function(req,res){
Machine.find().distinct('Brand', (err, items) => {
    if (err) {
        console.log(err);
        return res.status(400).send({ status: 'ko', data: {msg: err.message }});
        console.log(err);
    }
    console.log(items);
    res.status(200).send({status: 'ok', data: {msg: 'Brands available', brand:items}});
});
});

服务响应为 200,但作为 json 响应,我收到一个空数组

{
"status": "ok",
"data": {
    "msg": "Brands available",
    "brand": []
}

}

为什么数组是空的? 如何将我在 robomongo 上运行的 mongo 查询的相同响应放入数组中? 我也尝试过 find() 并且 ruslt 是相同的:一个空数组 []

router.get('/machine', function(req,res){
Machine.find({}, (err, machine) => {
    if (err) {
        console.log(err);
        return res.status(400).send({ status: 'ko', data: {msg: err.message }});
    }
    res.status(200).send({status: 'ok', data: {msg: 'Lista machine', machine: machine}});
});

}); 这是我的模型:

var db = require('../config/db.js');


var MachineSchema = db.Schema({
Brand: {type: String, required: true},
Model: {type: Number, required: true},
Version:{type: String, required: true},
Hp: {type: String, required: true}

});

db.model('Machine', MachineSchema);

module.exports = db.model('Machine');

感谢您的帮助 最好的,

【问题讨论】:

  • console.log(items); 打印什么?
  • Hi Sid,打印“[ ]”数组为空。我试过长度,结果是0;但在 robomongo 上,相同的查询填充了数组
  • 你可以试试Machine.find({}).distinct('Brand', (err, items) 确定一下,让我知道
  • 我尝试过,但反应相同
  • Machine.distinct('Brand', (err, items) 如果你也可以检查这个,试着弄清楚;)

标签: arrays node.js mongodb distinct


【解决方案1】:

这似乎应该有效,而且您收到回复的事实是一个好兆头。我的第一个建议是确保集合名称与您的数据库正确匹配。我刚刚测试了一段代码(获取一个名为“UserS”的集合),在这种情况下,MongoDB 似乎不会抛出错误,而是简单地创建一个新的空集合,并使用提供的名称。

编辑:如果您使用不同的库获得填充响应,则还要仔细检查库的初始化以确保其命中正确的数据库等。

【讨论】:

  • 在我的情况下,默认情况下 shell 连接到 admin db,这导致了这个问题。 MongoDB 中此类查询的不存在集合应该有警告。
猜你喜欢
  • 2020-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-18
  • 1970-01-01
相关资源
最近更新 更多