首先为我糟糕的英语找借口,但我会尽我最大的努力去解释。我是一名学生,正在尝试使用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",
...
...
...
},
...
...
...
]
]
这就是问题所在。*为什么如果我执行查询,它会返回我所有的数据库,而不使用过滤器?我有很多查询的组合,它总是返回给我所有的db或空数组?我需要这样的结果:
{
"titulo_restaurante": "example1",
...
...
...
}
发布于 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" } } })
因此,没有错误的查询是:
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)
。
https://stackoverflow.com/questions/52997717
复制相似问题