node.js - 在流星启动期间访问 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)
有人有解决方案吗?
解决方案
您出现错误的原因不是因为您在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 连接的更多说明,请查看此处。
推荐阅读
- excel - 使用 VBA 从 Excel 工作表中的列表中打开文件夹
- r - 按组返回日期范围
- angular - 可以在 setInterval() 函数中订阅 Angular Inbuilt observable 吗?
- jupyter-notebook - 如何删除 jupyter notebook 中的所有降价单元格?
- javascript - 如何从事件冒泡的孩子中删除事件侦听器
- excel-formula - 使用 Excel 公式查找评级指数之间的差异
- javascript - 基于两个值的打字稿中的数组迭代
- acumos - Acumos Boreas 安装失败
- android - 如何创建一个像 youtube 这样的应用程序来下载和显示视频
- android - gradlew 命令显示没有结果