mongoose查询数据库找到文档删除其_id无效
发布于 7 年前 作者 yuwanlin 5642 次浏览 来自 问答
postModel.findOne({
      "name": name,
    }, function(err, doc) {
      if(err){
        return callback(err);
      }
      delete doc._id; //删除掉原来的_id, 这里删除掉_id后,其doc._id仍然存在
      console.log(doc.id);
      // etc.****
})

如上所述,我在找到那个doc后想要删除它的_id属性,然后更新它自己。继而通过doc的一些属性得到另外一个document,然后保存。这样后面一个document就复制了doc的一些属性(通过复制)。问题是

  • 使用delete doc._id后,其依然存在,这样我得到的document_id和doc的_id是一样的,形成了覆盖。
  • 我在new Schema({ _id: Schema.Types.ObjectId })添加了_id字段后,得到的结果是一样的。 360反馈意见截图16411209109133124.png
  • 如果使用mongodb来操作,这样就没有问题,得到的结果是undefined

我该怎么做? 有会的哥哥姐姐帮忙解答一下吗

10 回复

搞了好长时间了唉…

有人帮帮我吗

找个微信或者qq群 发个红包瞬间搞定,我觉得10块以内肯定搞得定

唉,还是得自己回答。发起了一个issue,这是回答。

using delete on mongoose objects is kinda weird because they aren’t POJOs, they are mongoose documents with a bunch of getters and setters.

Mongoose actually tries very hard to prevent you from modifying the document’s id if you load the doc from the server. Can you tell me what you’re trying to do that requires you to remove the doc’s _id? There’s probably an alternative approach.

大致是说,mongoose中的document不是简单的对象,他们是getter和setter。所以使用delete看起来很奇怪。使用doc.set()代替。 删除_id后,我做了update操作,这样就出现问题了。

我的解决方法:重新new一个对象newDoc,复制doc的一些属性到newDoc.

issue

@jiangzhuo 可以的。。

你是看的改版之前的那个blog么

因为查询出来的是一个MongooseDocuments对象,如果要获得普通对象的话,需要用lean()方法 lean()

new Query().lean() // true
new Query().lean(true)
new Query().lean(false)

Model.find().lean().exec(function (err, docs) {
  docs[0] instanceof mongoose.Document // false
});

查找数据的时候直接把id过滤掉

Mongoose Model有个toObject方法,可以转换成plain javascript object 的,直接查出来的,是有getter和setter的,直接赋值什么的,不会按预期生效的。你可以试试严格模式,估计会报错的

直接这样

postModel.findOne({
      "name": name,
    }).lean().exec(function(err, doc) {
      if(err){
        return callback(err);
      }
      delete doc._id;
      console.log(doc.id);
      // etc.****
})
回到顶部