Mongo使用对象作为值删除文档

时间:2018-03-30 16:42:59

标签: javascript mongodb

您好我在使用对象

从MongoDb删除文档时遇到问题

这就是我的意思

const deleteTrimByName = function (db, callback) {
  // Get the documents collection
  const collection = db.collection(documentName)
  // Insert some documents
  console.log(trimNameToDelete)
  collection.deleteOne({Video_trim: trimNameToDelete}, function (err, result) {
    assert.equal(err, null)
    assert.equal(1, result.result.n)
    console.log('Removed the document')
    callback(result)
  })
  fs.unlink('./public/videos/cut-videos/' + documentName + '/' + trimNameToDelete.trimName + '.mp4', (err) => {
    if (err) {
      console.log('failed to delete local image:' + err)
    } else {
      console.log('successfully deleted local image')
    }
  })
}

其中trimNameToDelete的计算结果为

{"trimName":"cut2","startTime":"00:00:05","endTime":"00:00:15"}

并且mongo文档在shell中显示为

{ "_id" : ObjectId("5abe67897a9b9e0933c64acd"), "Video_trim" : { "trimName" : "cut2", "startTime" : "00:00:05", "endTime" : "00:00:15" } }

我得到的错误是

AssertionError [ERR_ASSERTION]: 1 == 0

由于技术原因,使用Id不能用于删除。

1 个答案:

答案 0 :(得分:0)

啊我发现了问题,我需要解析trimNametoDelete,愚蠢的错误,我将trimNametoDelete作为字符串发送。

const deleteTrimByName = function (db, callback) {
  // Get the documents collection
  const collection = db.collection(documentName)

  console.log('>>>>>' + trimNameToDelete)
  collection.deleteOne({Video_trim: JSON.parse(trimNameToDelete)}, function (err, result) {
    assert.equal(err, null)
    assert.equal(1, result.result.n)
    console.log('Removed the document')
    callback(result)
  })
  fs.unlink('./public/videos/cut-videos/' + documentName + '/' + JSON.parse(trimNameToDelete).trimName + '.mp4', (err) => {
    if (err) {
      console.log('failed to delete local image:' + err)
    } else {
      console.log('successfully deleted local image')
    }
  })
}