Mongoose查询:删除"_id"属性,在结果中保留虚拟属性"id"

Cla*_*u S 6 mongodb node.js

我正在运行Express.js应用程序,我有以下设置:

models.js

var schemaOptions = {
    toJSON: {
      virtuals: true
    },
    toObject: {
        virtuals: true
    }
};

var modelSchema = new mongoose.Schema({
    name     : { type: String, required: true }

}, schemaOptions);

modelSchema.virtual('id').get(function() { return this._id; });
Run Code Online (Sandbox Code Playgroud)

controllers.js

exports.getModel = function(req, res) {
    Model.find().select('name').exec(function(err,model) {
        if (err) {
            return res.status(500).json({errors:err, message: 'Internal server error'});
        }
        return res.status(200).json({model: model});
    });
};
Run Code Online (Sandbox Code Playgroud)

上述查询的结果如下:

{ "_id":"dakjdjkakda", "name":"MontyPython", "id":"dakjdjkakda" } 
Run Code Online (Sandbox Code Playgroud)

因为我在modelSchema中定义了Virtual属性.

如果我将查询select语句更改为:

Model.find().select('-_id name').exec(function(err,model) {}
Run Code Online (Sandbox Code Playgroud)

结果将是:

{"name":"MontyPython", "id":null }
Run Code Online (Sandbox Code Playgroud)

我相信这是因为Virtual属性指向_id属性.

我的问题是,如何删除查询中的_id属性,但保留我创建的id别名?

小智 5

你不能这样做。MongoDB 要求按照文档_id提供属性。

您的选择是使用虚拟属性(如示例中所示),也许还可以使用$project来隐藏查询结果中的字段。

否则,您的 mongo 驱动程序(例如 Mongoose)应该能够隐藏或重命名所需的字段或属性。


Tho*_*Lee 5

如果你使用猫鼬,

您可以处理何时toJSON,您可以决定它的显示方式,但您不能在查询中提及它.

Model.find().select('name').exec(function(err,model) {}

 new mongoose.Schema(yourSchema, {
    toJSON: { 
       transform: function(doc, ret) {
         ret.id = ret._id;
         delete ret._id;
       }
     }
   );}
Run Code Online (Sandbox Code Playgroud)


kbo*_*oom 5

您可以使用全局方法。试试这个:

mongoose.plugin((schema) => {
  schema.options.toJSON = {
    virtuals: true,
    versionKey: false,
    transform(doc, ret) {
      ret.id = ret._id;
      delete ret._id;
    }
  };
});
Run Code Online (Sandbox Code Playgroud)