JS/MongoDB:如何通过给定的父标题删除所有嵌套文档



在我的mongoDB中,有一些主要文档和一些子文档:

{ _id: 'KZg2RgcnxdfYbAoog',
title: 'Article Sample',
type: 'articles' }
{ _id: 'YbAoogKZg2Rgcnxdf',
parent: 'KZg2RgcnxdfYbAoog' }

现在,我需要使用主文档的标题删除完整的数据集。

所以我的方法是首先获取与给定标题数组匹配的所有文档。使用这些 ID,我试图删除所有带有此idparent的文档。 但是有了这段代码,我没有得到任何删除。articles似乎没有定义...

此外,对于这个简单的任务,完整的代码看起来非常庞大。这能做得更聪明一点吗?

MongoClient.connect(mongoUrl, function (err, db) {
expect(err).to.be.null
console.log('Connected successfully to server: ' + mongoUrl)
var articles = db.collection('articles')
var titleArray = ['Article Sample', 'Another sample']
articles.find({ title: { $in: titleArray } }).toArray((err, docs) => {
if (err) console.warn(err)
if (docs && docs.length > 0) {
docs.forEach(doc => {
articles.remove(
{
$or: [
{ _id: doc._id },
{ parent: doc._id },
{ main: doc._id }
]
},
(err, numberOfRemovedDocs) => {
console.log(numberOfRemovedDocs)
}
)
})
}
})
db.close()
})

您在找到任何内容之前关闭了数据库连接。articles.find是异步的,您立即db.close()它之后。

它应该是这样的:

articles.find({ title: { $in: titleArray } }).toArray((err, docs) => {
if (err) console.warn(err)
if (docs && docs.length > 0) {
Promise.all(
docs.map(doc => 
articles.remove(
{
$or: [
{ _id: doc._id },
{ parent: doc._id },
{ main: doc._id }
]
}
)
)
)
.then((res)=>{
res.map((res)=>{console.log(res.result.n)}); //numberOfRemovedDocs per title
db.close()
})
.catch(()=>{db.close()})
} else {
db.close()
}
})

最新更新