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!