[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)
有人知道了吗?
出现错误的原因不是因为您正在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();
});
})