Unable to write to Atlas using Mongoose

I am able to connect to MongoDB. I have an empty free Cluster0. I am unable to create a database and save a document with the snippet below. I get a “MongoError: (Unauthorized) not authorized
on admin to execute command”. There are similar questions on Stackoverflow, most discussing different connection strings, none of which has worked for me. Your help is appreciated and thanks in advance.

var mongoose = require("mongoose");
var string = "mongodb+srv://admin:xxxxxxxxxx@cluster0.xxxxxxx.mongodb.net/database1";
mongoose.connect(string)
    .then(function () {
        console.log("Connected to MongoDB.")
    })
    .catch(function (e) {
        console.log(e);
    });
var schema1 = new mongoose.Schema({
    prop1: Number,
});
var Document = mongoose.model("Document", schema1);
var document = new Document({
    prop1: 1,
});
document.save();

Hi @Bernie_Ackerman - Welcome to the community :wave:

Is this the only code you’re executing?

I copied it and replaced the connection string to specify my own test free tier cluster and a document was inserted.
Before execution, empty collection:

testdb2> db.documents.find()
/// No documents

After executing the provided code snippet:

testdb2> db.documents.find()
[ { _id: ObjectId("648ba9487c0121ce02451cbb"), prop1: 1, __v: 0 } ]

Regards,
Jason

1 Like

@Jason_Tran Thank you for your reply. Yes, this is the only code being executed. After trying for hours last night, I tried again this morning, and it worked. A database and collection were created, although the document wasn’t saved and I got a diffrent error. I changed the name of the last variable, thinking “document” may be a reserved word, and it worked. Thanks again.

1 Like

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