我想将 promisify 与 MongoDB 一起使用。我最后尝试了代码,连接正常,但函数 insertOne 不行。有人可以帮我吗?最好解释一下原因,以及使用 '.db().collection()' 时的上下文是什么,我应该如何使用如下代码使函数 promisify:
a().b().c().d()
这是我的代码,如下所示。
import "babel-polyfill"
const mongoClient = require('mongodb').MongoClient
const util = require('util')
const chalk = require('chalk')
const url = 'mongodb://localhost:27017'
const dbName = ''
const collName = ''
let connect = util.promisify(mongoClient.connect).bind(mongoClient)
let insertOne = util.promisify(mongoClient.insertOne)
.bind(mongoClient)
const main = async () => {
try {
await connect(url)
insertOne({a100: 1}).db(dbName).collection(collName)
} catch (err) {
console.log(chalk.red(err.toString()))
}
mongoClient.close()
}
main()
MongoDB 驱动程序已经返回了承诺(请参阅文档 http://mongodb.github.io/node-mongodb-native/3.0/api/MongoClient.html#.connect)。你不需要使用util.promisify
。另外,你不链接db
and collection
类似的查询insertOne
。恰恰相反。
例如:
client = await mongoClient.connect(url)
client.db(dbName).collection(collName).insertOne({a100: 1})
(注意,如果您使用旧的 mongodb 节点驱动程序版本 2.2,则略有不同,因为 connect 返回一个 db 对象 -2.2 的文档 http://mongodb.github.io/node-mongodb-native/2.2/api/MongoClient.html#.connect)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)