猫鼬“_id”字段无法删除

mongoose "_id" field can't be deleted

我想 return "id" 字段而不是“_id”,使用

中的解决方案

MongoDB: output 'id' instead of '_id'

以下是我的代码:

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

但是响应仍然有字段"id"和“_id”,看来delete没有生效。为什么?

在 Mongoose 上,"id" 属性 是默认创建的,它是一个返回“_id”值的虚拟对象。你不需要自己做。
如果你想禁用 "id" 属性 的自动创建,你可以在定义架构时这样做:

var schema = new Schema({ name: String }, { id: false })

对于_id字段,可以在新建Mongoose对象时告诉Mongoose默认不创建,{_id: false}属性。但是,当您 .save() MongoDB 中的文档时,服务器将为您创建一个 _id 属性。
参见:http://mongoosejs.com/docs/guide.html#_id

我在我的代码中所做的是创建一个 instance method 类似 returnable 的东西,returns 一个纯 JS 对象,只有我需要的属性。例如:

userSchema.methods.returnable = function(context) {
    // Convert this to a plain JS object
    var that = this.toObject()

    // Add back virtual properties
    that.displayName = this.displayName

    // Manually expose selected properties
    var out = {}
    out['id'] = that._id

    var expose = ['name', 'displayName', 'email', 'active', 'verified', 'company', 'position', 'address', 'phone']
    for(var i in expose) {
        var key = expose[i]
        out[key] = that[key]

        // Change objects to JS objects
        if(out[key] && typeof out[key] === 'object' && !Array.isArray(out[key])) {
            // Change empty objects (not array) to undefined
            if(!Object.keys(out[key]).length) {
                out[key] = undefined
            }
        }
    }

    return out
}

我估计你需要的是toJSON。这应该可以满足您的要求:

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