I have the following code to modify a user account in my application:
"use strict";
var mongoose = require("mongoose");
mongoose.set("debug", true);
mongoose.connect(process.env.MONGO_URL, {
auth: {
user: process.env.MONGO_USER,
password: process.env.MONGO_PASSWD,
},
useNewUrlParser: true,
useUnifiedTopology: false,
});
var db = mongoose.connection;
var schema = mongoose.Schema;
var user_schema = new schema(
{
id: { type: String, required: true, unique: true },
username: { type: String, required: true },
name: String,
email: String,
phone: String,
created: Date,
modified: Date,
},
{ strict: false }
);
var query = user.where({ id: user_id }),
user_id = "93", // temporarily hard-coded as an example
user_modified = null,
result = -1; // failure
db.on("error", console.error.bind(console, "connection error:"));
db.once("open", function () {
async () => {
await query.findOne(function (err, user) {
if (err) {
console.log(err);
}
if (user) {
user.modified = Date();
user_modified = user;
}
});
if (user_modified) {
try {
let save_user = await user_modified.save();
if (save_user) {
result = 1; // success
}
} catch (err) {
console.log(err);
}
}
console.log(result);
};
});
This assumes that the user account 93
is already created in the MongoDB database:
{
"_id": ObjectId("5e7d3c3d0a6467c8b554abf4"),
"id": "93",
"username": "foo",
"name": "bar",
"email": 'baz@mail.com',
"phone": '1234567890',
"created": "2000-01-01 01:10:01.553",
"modified": "2000-01-01 01:10:01.553"
}
I have this code running on an ec2 instance in us-east-2, eu-west-1, and ap-southeast-1. I am also based in the Eastern United States.
Here is my MongoDB connection string:
MONGO_URL: "mongodb://us-east-2.foo.com:27017,eu-west-1.foo.com:27017,ap-southeast-1.foo.com:27017/bar?authSource=admin&replicaSet=bz0&readPreference=secondary"
When I hit the us-east-2 instance, it always returns 1
(success) for me. But if I try to hit the eu-west-1 or ap-southeast-1 instance(s), it inconsistently returns -1
(failure).
Note: I have also experienced failures by using a single MongoDB instance instead of a ReplicaSet. It fails whenever I try to connect across regions.
Reference(s):