node.jsmongodbmeteormeteor-collection2

Access mongodb during meteor startup possible?


is there a way to access the mongodb during the Meteor.startup()

I need to insert/update a document in a collection during the Meteor.startup()

I tried:

// https://www.npmjs.com/package/mongodb
const MongoClient = require('mongodb').MongoClient; 

// await may be missing but when i use await, i get a reserved keyword error
const mongodb = MongoClient.connect(process.env.MONGO_URL)

mongodb.collection('collection').insertOne(objectData)

// Error
// TypeError: mongodb.collection is not a function
// at Meteor.startup (server/migrations.js:1212:23)

and

const col = Mongo.Collection('collection');

// Error
// TypeError: this._maybeSetUpReplication is not a function
// at Object.Collection [as _CollectionConstructor] (packages/mongo/collection.js:109:8)

Anyone got a solution?


Solution

  • The reason you are having the error is not because you are accessing mongodb in the startup method, it's because the MongoClient.connect method is asynchronous, consequently, you can only access your mongodb collections after the connect method resolves. You should try something like this instead:

    const MongoClient = require('mongodb').MongoClient;
    
    MongoClient.connect(process.env.MONGO_URL, null, (err, client) => {
      const db = client.db();
      // You can now access your collections
      const collection = db.collection('collection');
      // NOTE: insertOne is also asynchronous
      collection.insertOne(objectData, (err, result) => {
        // Process the reult as you wish
        // You should close the client when done with everything you need it for
        client.close();
      });
    })
    

    For more explanation on connecting via MongoClient, check here.