This module acts as a singleton that you can use with async
/await
in a Meteor-like "synchronous" fashion to interact with MongoDB collections.
Intended usage is for CLI or "serverless" (Lambda/GCF) apps that need to interact with Meteor-based apps to generally make life easier while developing. There are no projections, all the find
s are automatically returned as arrays.
I use this in my own internal projects so it's pretty simple, but feel free to contribute.
Set the DB in the singleton.
Set the Mongo client in the singleton.
Get the DB from the singleton.
Get the Mongo client from the singleton.
Create a new collection
In your entry point:
const Mongo = require('meteor-mongodb-collections'); // This creates the singleton.
const MongoClient = require('mongodb').MongoClient;
const doStuff = require('./doStuff.js');
async function connect() {
try {
const client = await MongoClient.connect(config.MONGO_URL);
const db = client.db(client.s.options.dbName);
Mongo.setDb(db); // Set the db in the singleton.
Mongo.setClient(client); // ..and the client.
await doStuff();
}
catch(err) {
console.error(err);
process.exit();
};
}
connect();
After that you can declare collections:
const Mongo = require('meteor-mongodb-collections');
const Users = new Mongo.Collection("users");
module.exports = Users;
And use them:
const Users = require('./collections/Users.js');
async function doStuff() {
const user = await Users.findOne({ "emails.address": "[email protected]" });
console.log(user);
const updateOp = await Users.update({
"emails.address": "[email protected]"
}, {
$set: {
"foo": "bar"
}
});
}
module.exports = doStuff;