【问题标题】:Access mongodb during meteor startup possible?在流星启动期间访问 mongodb 可能吗?
【发布时间】:2020-05-26 16:22:11
【问题描述】:

有没有办法在Meteor.startup()期间访问mongodb

我需要在Meteor.startup() 期间在集合中插入/更新文档

我试过了:

// 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)

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

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

有人有解决办法吗?

【问题讨论】:

    标签: node.js mongodb meteor meteor-collection2


    【解决方案1】:

    您遇到错误的原因不是因为您在startup方法中访问mongodb,而是因为MongoClient.connect方法是异步的,因此您只能在connect方法解决后访问您的mongodb集合.你应该尝试这样的事情:

    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();
      });
    })
    

    有关通过 MongoClient 连接的更多说明,请查看here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-29
      • 2012-06-27
      • 2014-02-25
      • 1970-01-01
      • 2015-08-11
      • 1970-01-01
      • 2019-10-03
      • 1970-01-01
      相关资源
      最近更新 更多