Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript JS/MongoDB:如何根据给定的父标题删除所有嵌套文档_Javascript_Mongodb - Fatal编程技术网

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

Javascript JS/MongoDB:如何根据给定的父标题删除所有嵌套文档,javascript,mongodb,Javascript,Mongodb,在我的mongoDB中有一些主要文档和一些子文档: { _id: 'KZg2RgcnxdfYbAoog', title: 'Article Sample', type: 'articles' } { _id: 'YbAoogKZg2Rgcnxdf', parent: 'KZg2RgcnxdfYbAoog' } 现在,我需要使用主文档的标题删除完整的数据集 因此,我的方法是首先获取与给定标题数组匹配的所有文档。使用这些id,我试图删除所有具有此id或父项的文档。 但是使用这段代码我不会得到任何

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

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

{ _id: 'YbAoogKZg2Rgcnxdf',
parent: 'KZg2RgcnxdfYbAoog' }
现在,我需要使用主文档的标题删除完整的数据集

因此,我的方法是首先获取与给定标题数组匹配的所有文档。使用这些id,我试图删除所有具有此
id
父项的文档。
但是使用这段代码我不会得到任何删除<代码>文章
似乎未定义

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

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()
    }
  })