首页 > 解决方案 > Nodejs MongoDb query returns everything instead of matching document

问题描述

Json Structure:

 {"address": {"building": "1007", "coord": [-73.856077, 40.848447], "street": "Morris Park Ave", "zipcode": "10462"}, "borough": "Bronx", "cuisine": "Bakery", "grades": [{"date": {"$date": 1393804800000}, "grade": "A", "score": 2}, {"date": {"$date": 1378857600000}, "grade": "A", "score": 6}, {"date": {"$date": 1358985600000}, "grade": "A", "score": 10}, {"date": {"$date": 1322006400000}, "grade": "A", "score": 9}, {"date": {"$date": 1299715200000}, "grade": "B", "score": 14}], "name": "Morris Park Bake Shop", "restaurant_id": "30075445"},...



const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
// Connection URL
const url = 'mongodb://localhost:27017'; 
// Database Name
const dbName = 'restaurant';
MongoClient.connect(url, function(err, client) {
    const db = client.db(dbName);
    const collection = db.collection('restaurants');
    collection.find({}, {"restaurant_id": "40386837"}).toArray(function(err,docs){
        console.log(docs)    
    });
  });

Output:

enter image description here

There is only one record that matches the criteria "restaurant_id": "40386837" but I am getting all of it.

标签: javascriptnode.jsmongodbnpm

解决方案


我认为您的查询应该是您通过的第一件事,而不是第二件事:

find(query, projection)

所以:

collection.find({"restaurant_id": "40386837"})

请参阅文档:https ://docs.mongodb.com/realm/mongodb/actions/collection.find/


推荐阅读