Can query MongoDB using MongoClient, but not with Mongoose

Hi guys, could somebody give me a hand with understanding where I went wrong with using Mongoose? I am stuck for 2 days already.

Here is my code in MongoClient, and it works:

const { MongoClient, ObjectId } = require('mongodb')

const main = async () => {
    const uri = "mongodb+srv://weareandrei:<password>@omega.owkrpxa.mongodb.net/?retryWrites=true&w=majority&appName=AtlasApp";
    const client = new MongoClient(uri);

    try {
        await client.connect();
        console.log('Connected successfully');

        const database = client.db('User');
        const collection = database.collection('User');

        const result = await collection.findOne({username: 'user'});

        if (result) {
            console.log('Retrieved document:', result);
        } else {
            console.log('Document not found');
        }
    } catch (e) {
        console.error('Error:', e);
    } finally {
        await client.close();
        console.log('Connection closed');
    }
}

main()

And here is a similar code that uses mongoose:

const {mongoose} = require('mongoose');

const main = async () => {
    const mongoString = 'mongodb+srv://weareandrei:<password>@omega.owkrpxa.mongodb.net/?retryWrites=true&w=majority&appName=AtlasApp'

    try {
        mongoose.connect(mongoString, { useNewUrlParser: true, useUnifiedTopology: true })
            .then(() => {
                console.log('Database Connected');
            })
            .catch((error) => {
                console.error('Database Connection Error:', error);
            });

        mongoose.set("strictQuery", false);

        const Schema = mongoose.Schema

        const UserModelSchema = new Schema({
            documentationId : {
                type: String
            },
            password : {
                type: String
            },
            username : {
                type: String
            }
        })

        const UserModel = mongoose.model("User", UserModelSchema, 'User')

        const result = await UserModel.findOne({username: 'user'});

        if (result) {
            console.log('Retrieved document:', result);
        } else {
            console.log('Document not found');
        }
    } catch (e) {
        console.error('Error:', e);
    } finally {
        await mongoose.connection.close();
        console.log('Connection closed');
    }
}

main()

If I run the first one, I get :

Connected successfully
Retrieved document: {
  _id: new ObjectId("652367f3e9a268c7fc1e6efa"),
  username: 'user',
  password: 'pass',
  documentationId: '6523592fd730e1f9120fbef6'
}
Connection closed

However, the second code returns:

Database Connected
Document not found
Connection closed

Here is the json object of my User.User collection from mongoDB. I believe I defined the model correctly.

{
  "_id": {
    "$oid": "652367f3e9a268c7fc1e6efa"
  },
  "username": "user",
  "password": "pass",
  "documentationId": "6523592fd730e1f9120fbef6"
}

Thank you in advance!

Hello @Andrei_Mikhov, Welcome to the MongoDB community forum,

It looks like you missed to specify the database name in the Mongoose code. So by default, it will connect with the test database.

Hey @turivishal , thatks for the reply!
Could you elaborate pls? I can’t se where I missed it. It is specified in URI I guess? If you are talking about the model, then in model I included the db and collection name…

Hello @Andrei_Mikhov,

You have to specify the Database name in the connection string:

mongodb+srv://weareandrei:<password>@omega.owkrpxa.mongodb.net/<dbName>?retryWrites=true&w=majority&appName=AtlasApp

Or you can specify in options of connect method:

mongoose.connect(mongoString, { dbName: "User", useNewUrlParser: true, useUnifiedTopology: true })

https://mongoosejs.com/docs/connections.html#options


const UserModel = mongoose.model("User", UserModelSchema, 'User')

The first parameter is for the Model name and the last one is for the collection name!
https://mongoosejs.com/docs/6.x/docs/api/mongoose.html#mongoose_Mongoose-model

You can always refer to the documentation.

1 Like

@turivishal Thanks a lot! This worked now.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.