Reputation: 127
I have an existing node/express server using mongoose to connect to MongoDB. Everything is working fine.
I'd like to create a separate node/express server to run cron jobs (sending emails, push notifications, etc.)
First of all, would this be a good implementation? (I've looked over message queues like RabbitMQ but seems a bit overkill for what I need.)
Second, I am having difficulty getting my second node/express app connected to the existing MongoDB. I've tried connecting with mongoose and also directly with mongodb and I haven't had much luck.
Here's an example of one of the many things I've tried:
const client = new MongoClient(keys.mongoURI, { useUnifiedTopology: true });
async function run() {
try {
// Connect the client to the server
const db = await client.connect();
// Establish and verify connection
await client.db("my-db").command({ ping: 1 });
console.log("Connected successfully to server");
const users = await db.users.find()
await console.log(users)
} finally {
// Ensures that the client will close when you finish/error
await client.close();
}
}
I get find is not a function
Any pointers?
Upvotes: 0
Views: 397
Reputation: 1809
For MongoDB driver this should work:
const client = new MongoClient(keys.mongoURI, { useUnifiedTopology: true });
async function run() {
try {
// Connect the client to the server
const db = await client.connect();
// Establish and verify connection
await client.db("my-db").command({ ping: 1 });
console.log("Connected successfully to server");
const users = await db("my-db").collection("users").find();
console.log(users);
} finally {
// Ensures that the client will close when you finish/error
await client.close();
}
}
While for mongoose, this approach should work:
// You have your mongoose connection to the database and then
async function run() {
try {
... you connect to your database and ping it ...
const users = await mongoose.connection.db.collection("users").find();
console.log(users);
} finally {
// Ensures that the client will close when you finish/error
await client.close();
}
}
Please, let me know if you found any other issue
Upvotes: 1