【发布时间】:2019-04-20 01:35:47
【问题描述】:
我想将唯一值存储到集合中。我正在使用 Node.js 和 MongoDb。但是,如果我尝试在 Find 承诺中插入,那么它会显示“MongoError:服务器实例池已被破坏”
而且我无法访问 Find promise 之外的集合中的数据。 请帮助我,我真的不明白如何解决这个异步模式。
function addToDBAs( data ){
mongo_client.connect(url, (err, db)=>{
if(err)
console.log(err)
else{
var dbo = db.db('uniqueSet')
dbo.createCollection('entities',(err, res)=>{
if(err)
console.log(err)
else{
console.log("collections created")
let collection = dbo.collection('entities')
let dataObjs = []
collection.find().toArray((err, items) => {
data = new Set( data, items )
data = Array.from(data)
data.map(entity => dataObjs.push({name: entity}))
dbo.collection('entities').insertMany(dataObjs)
console.log(items)
})
db.close();
}
})
}
})
}
【问题讨论】:
-
虽然这里的问题确实是在
insertMany()操作完成之前调用close(),但主要的因果问题是在功能单元内建立连接然后关闭只是不好的做法。请参阅 How to properly reuse connection to Mongodb across NodeJs application and modules 以了解您实际上连接 一次,然后在应用程序的其余部分运行时共享连接引用。