• mongoDB通过_id删除doc


     db.collection('infochanges').remove({"_id":idvalue}).then(function(){})

    会报错,这里需要将idvalue转换成mongodb默认的_id字段的objectid类型
    于是,引入模块(mongoDB3.6)

     var ObjectId = require('mongodb').ObjectID;//Work

    其他的mongoDB版本可尝试

     var ObjectId = require('mongodb').ObjectId;//Work

    引用完成之后

     db.collection('infochanges').remove({"_id":{"_id":ObjectId(idvalue)}).then(function(){})
    此时,你会发现并不能通过上述操作成功删除数据,而是报错:
     TypeError:Cannot convert undefined or null to object
    

    重点:请使用findAndRemove

     db.collection('infochanges').findAndRemove({"_id":ObjectId(index)}).then(function(){})

    通过_id删除docs要用findAndRemove,remove不起作用(3.6版本)

    上面给的写法,也可以省略  .then()。 直接通过传参的方式。 都是回调函数,等待异步执行完才执行。

    例: 

    db.collection('infochanges').findAndRemove({"_id":ObjectId(index)}), function(){})

    【注】  findAndRemove 现在也被弃用了,被更换为findOneAndDelete

    希望能给各位遇到同样问题的道友一些帮助,也请各位大神多多指点,轻喷。

  • 相关阅读:
    MM and Desinger
    db subsequent and synchronization(transfer)
    Thread concepts
    Threads concepts
    lucene article
    primary key
    lucene
    page procedure
    connection pool
    page procedures
  • 原文地址:https://www.cnblogs.com/taohuaya/p/9900163.html
Copyright © 2020-2023  润新知