是否可以在流星启动期间访问mongodb?

问题描述 投票:0回答:1

[Meteor.startup()期间是否有访问mongodb的方法

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

我尝试过:

const MongoClient = require('mongodb').MongoClient; // https://www.npmjs.com/package/mongodb
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个回答
0
投票

出现错误的原因不是因为您正在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();
  });
})
© www.soinside.com 2019 - 2024. All rights reserved.