可以在流星启动期间访问 mongodb 吗?
Access mongodb during meteor startup possible?
有没有办法在 Meteor.startup()
期间访问 mongodb
我需要在 Meteor.startup()
期间 insert/update 集合中的文档
我试过:
// 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)
有人有解决办法吗?
您出错的原因不是因为您在 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。
有没有办法在 Meteor.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)
有人有解决办法吗?
您出错的原因不是因为您在 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。