まず第一に私の悪い英語の言い訳ですが、私は自分自身を説明するために最善を尽くします。これまで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();
});
});
});
そして私のdbはこのようなものです:
[
"_id" : "345678987654",
"restaurantes": [
{
"titulo_restaurante": "example1",
...
...
...
},
{
"titulo_restaurante": "example2",
...
...
...
},
...
...
...
]
]
そして、これが問題です。¿なぜクエリを実行すると、フィルターなしですべてのデータベースが返されるのですか?私はクエリの組み合わせがたくさんあり、それは常にすべてのデータベースまたは空の配列を私に返しますか?結果として、次のようなものが必要です。
{
"titulo_restaurante": "example1",
...
...
...
}
クエリコードには2つのエラーがあります。
new
コマンドがありません。_idのドキュメントを見つけると、特定の初期化(id文字列)を持つObjectIDオブジェクトが見つかるため、検索するオブジェクトを作成する必要があります:new ObjectId( 'idString')、結果適切なドキュメントを見つけるためにdocuments_idと比較できるObjectIDになります(varObjectId = 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();
});
GET応答のres.send(result)
前db.close()
に追加します。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加