This may sound silly question, but I started learning mongoDB
and mongoosejs v7
. When I made a database, I chose to add sample data for practice. The problem is I don't know how to search for documents in the collection. I tried to use find
method but it needs a model
so I create the model
and pass the name of the collection that I want to search inside it.
as you can see it creates "test" database and put new collection. I don't want to make new collection I want to search inside other collection. Please answer my question if you understand it and know the solution.
You get an access to the connected database using a mongoose method on the current connection via the getClient()
method.
You can store it in a variable.
const client = mongoose.connection.getClient();
On this client object, you can access any database you would like to.
const client = mongoose.connection.getClient();
const db = await client.db('<any_database_name>');
Using this db
variable, you can now make any query to the database.
Eg.
const users = await db
.collection('users')
.find()
.toArray();
The .find()
method returns a cursor, which then needs to be transformed into an array, hence I have used the toArray()
method.
Here's a full example
const mongoose = require('mongoose');
mongoose
.connect('mongodb://localhost:27017/icard')
.then(async (result) => {
console.log('connected');
const client = mongoose.connection.getClient();
const users = await client
.db('school')
.collection('users')
.find()
.toArray();
console.log(users);
})
.catch((err) => {
console.log(err.message);
process.exit(0);
});