首页 > 解决方案 > 在流星启动期间访问 mongodb 可能吗?

问题描述

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

我需要在集合中插入/更新文档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.jsmongodbmeteormeteor-collection2

解决方案


您出现错误的原因不是因为您在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 连接的更多说明,请查看此处


推荐阅读