猫鼬"_id"字段不能删除 [英] mongoose "_id" field can't be deleted

查看:53
本文介绍了猫鼬"_id"字段不能删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要使用

中的解决方案返回"id"字段而不是"_id"

MongoDB:输出'id'而不是'_id'

以下是我的代码:

ScenicSpotSchema.virtual('id').get(function () {
    var id = this._id.toString();
    delete this._id;
    delete this.__v;
    return id;
});

但是响应仍然具有字段"id"和"_id",看来delete无效.为什么?

解决方案

我估计您需要的是toJSON.这应该做您想要的:

 schema.options.toJSON = {
  transform: function(doc, ret) {
    ret.id = ret._id;
    delete ret._id;
    delete ret.__v;
  }
}; 

I want to return the "id" field instead of "_id",using the solution in

MongoDB: output 'id' instead of '_id'

the following is my code:

ScenicSpotSchema.virtual('id').get(function () {
    var id = this._id.toString();
    delete this._id;
    delete this.__v;
    return id;
});

But the response still have the field "id" and "_id",It seems that the delete doesn't take effect. Why?

解决方案

I'm estimating what you need is toJSON. This should do what you want:

schema.options.toJSON = {
  transform: function(doc, ret) {
    ret.id = ret._id;
    delete ret._id;
    delete ret.__v;
  }
};

这篇关于猫鼬"_id"字段不能删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆