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

时间:2017-07-17 10:24:15

标签: javascript 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()
})

1 个答案:

答案 0 :(得分:0)

在找到任何内容之前,您正在关闭数据库连接。 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()
    }
  })