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.
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 eg coll = db['users']
and then perform operations against that collection object eg
c = coll.find({name:"foo"});
c.forEach(function(doc) {
printjson(doc);
});
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.