When connecting to MongoDB with a Node.JS application using express, how do you connect to just one collection if the database has multiple collections?
I have the following MONGODB_URI:
MONGODB_URI=mongodb srv://username:******@cluster0.dayw5.mongodb.net/phonebook?retryWrites=true&w=majority
The database "phonebook" has three collections, "numbers", "users" and "people". How do you change the MONGODB_URI to just connect to "numbers" ?
At the moment, the connection is successful, but nothing is being fetched.
CodePudding user response:
You don't; the connection URI is granular to the database only, in your case phonebook
. From the resources returned, you must specify a collection to access e.g. coll = db['users']
and then perform operations against that collection object e.g.
c = coll.find({name:"foo"});
c.forEach(function(doc) {
printjson(doc);
});
CodePudding user response:
Both answers given above are basically correct.
I tried to connect to an existing collection but was unable to do so. Instead, MongoDB automatically creates a new collection in the database and gives it a new, custom name: "people" in my case which I did not specify anywhere.