Mongodb和nodejs用express

问题描述 投票:0回答:1

首先,我的英语不好,但我会尽力解释自己。我是一名正在尝试使用express开发nodejs项目的学生,直到现在我在一个json文件中使用db作为数据库并通过它工作。但现在我想迁移到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",
        ... 
        ...
        ...
    },
    ...
    ...
    ...
]

]

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

{
        "titulo_restaurante": "example1",
        ... 
        ...
        ...
    }
node.js mongodb express
1个回答
0
投票

查询代码中有两个错误:

  • 你错过了new命令。当您找到_id的文档时,您将找到具有特定inizialization的ObjectID对象(谁是id字符串),因此您必须创建要搜索的对象: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();
    });

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

© www.soinside.com 2019 - 2024. All rights reserved.