【问题标题】:Mongodb and nodejs with express带有 express 的 Mongodb 和 nodejs
【发布时间】:2018-10-26 18:45:50
【问题描述】:

首先为我的英语不好找借口,但我会尽力解释自己。我是一个试图用 express 开发 nodejs 项目的学生,直到现在我在单个 json 文件中用作数据库并通过它工作。但现在我想迁移到 Mongodb。我已经用 "mongoimport --db RestauranteSin" --collection "Restaurante" --file 'filename'" 导入了我的数据库,所以它导入了。

我接下来要做的是创建一个新端点

app.get('/mongoAllRestaurants', (req, res) => {
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";

MongoClient.connect("mongodb://localhost:27017/", { useNewUrlParser: true },(err, db) => {
    if (err) throw err;
    var dbo = db.db("RestauranteSin");
    var ObjectId = require('mongodb').ObjectID; 
    dbo.collection("Restaurante").find({_id:ObjectId("5bd218627c5b747cdb14c51e"), restaurantes: {$elemMatch : {titulo_restaurante: "BarJanny"}}}).toArray((err, result) => {
      if (err) throw err;
      console.log(result[0]);
      res.send(result);
      db.close();
    });
});

});

我的数据库是这样的:

[
"_id" : "345678987654",
"restaurantes": [
    {
        "titulo_restaurante": "example1",
        ... 
        ...
        ...
    },
    {
        "titulo_restaurante": "example2",
        ... 
        ...
        ...
    },
    ...
    ...
    ...
]

]

这就是问题所在。 ¿为什么如果我进行查询,它会返回我所有的数据库而没有过滤器?我有很多查询组合,它总是返回给我所有的数据库或空数组?结果我需要这样的东西:

{
        "titulo_restaurante": "example1",
        ... 
        ...
        ...
    }

【问题讨论】:

    标签: node.js mongodb express


    【解决方案1】:

    查询代码有两个错误:

    • 您缺少new 命令。当你找到一个文件时 _id,您正在寻找具有特定初始化(谁是 id 字符串)的 ObjectID 对象,因此您必须创建该对象 您正在搜索:new ObjectId('idString'),结果将是 可以与文档 _id 进行比较的 ObjectID 以查找 正确的文档(请注意,使用 var ObjectId = require('mongodb').ObjectID; 您需要 mongodb 包的 ObjectID 类并将其分配给 var ObjectId)。

    • 不推荐使用 find 内部的投影。您可以使用 projection(),如下所示:db.collection('collectionName').find({ field: value }).project({ field: value }) 如果您的查询是:dbo.collection("Resturante").find({ _id: new ObjectId('5bd218627c5b747cdb14c51e') }).project({ restaurantes: { . $elemMatch: { titulo_restaurante: "BarJanny" } } })

    所以你没有错误的查询是:

    dbo.collection("Resturante")
        .find({ _id: new ObjectId('5bd218627c5b747cdb14c51e') })
        .project({ restaurantes: { $elemMatch: { titulo_restaurante: "BarJanny" } } })
        .toArray((err, result) => {
            if (err) throw err;
            console.log(result[0].restaurantes[0]); // { titulo_restaurante: 'BarJanny' }
            db.close();
        });
    

    db.close() 之前添加 res.send(result) 以获得 GET 响应。

    【讨论】:

    • 嗨,首先感谢您回答我的问题,我已经尝试过了,但我不知道为什么它一直向我返回整个数据库,不明白出了什么问题......它不是在查询.
    • 嗨,很高兴。我已经更改了响应,并且我亲自尝试了代码。现在它起作用了。我提到的第一个问题是正确的,但第二个问题是 .find() 内的投影已被弃用(请参阅新解决方案)。
    猜你喜欢
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-09
    • 2021-11-04
    • 2016-02-10
    相关资源
    最近更新 更多