首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Mongodb和nodejs with express

Mongodb和nodejs with express
EN

Stack Overflow用户
提问于 2018-10-26 04:36:29
回答 1查看 114关注 0票数 0

首先为我糟糕的英语找借口,但我会尽我最大的努力去解释。我是一名学生,正在尝试使用express开发nodejs项目,直到现在,我一直在使用单个json文件中的数据库,并通过它工作。但现在我想迁移到Mongodb。我已经用"mongoimport --db RestauranteSin“--collection "Restaurante”--file 'filename'“导入了我的数据库,所以它可以导入它。

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

代码语言:javascript
复制
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();
    });
});

});

我的数据库是这样的:

代码语言:javascript
复制
[
"_id" : "345678987654",
"restaurantes": [
    {
        "titulo_restaurante": "example1",
        ... 
        ...
        ...
    },
    {
        "titulo_restaurante": "example2",
        ... 
        ...
        ...
    },
    ...
    ...
    ...
]

]

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

代码语言:javascript
复制
{
        "titulo_restaurante": "example1",
        ... 
        ...
        ...
    }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-10-26 06:24:42

查询代码中有两个错误:

  • 您缺少new命令。当你对一个_id的文档进行查找时,你是在寻找一个具有特定初始化的ObjectID对象(谁是id字符串),所以你必须创建你正在搜索的对象: ObjectId('idString'),结果将是一个可以与文档_id进行比较的ObjectID,以便找到正确的文档(请注意,对于var ObjectId = require('mongodb').ObjectID;,你需要mongodb包的ObjectID类,并将其分配给var mongodb包并将其赋值给var mongodb包)。您可以使用projection(),如下所示:查询中的db.collection('collectionName').find({ field: value }).project({ field: value })是:dbo.collection("Resturante").find({ _id: new ObjectId('5bd218627c5b747cdb14c51e') }).project({ restaurantes: { . $elemMatch: { titulo_restaurante: "BarJanny" } } })

因此,没有错误的查询是:

代码语言:javascript
复制
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();
    });

在GET响应的db.close()之前添加res.send(result)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52997717

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档