【问题标题】:How to limit property returned after save?保存后如何限制返回的属性?
【发布时间】:2017-10-05 19:28:36
【问题描述】:

我正在尝试将保存的对象作为请求响应返回,但我不希望 Model.save() 函数返回整个对象,它返回的信息比我想要的多,例如 _id__v

我的请求代码是这样的:

function insertUser(req, res) {
   const userName = req.Body.name;

      User.save({ name : userName })
         .then(r => {  
            res.send(r);
         });
}

它正在休耕JSON 归还给我:

{
    _id: 590f529976aa6142d91870b7,
    name: 'blablabla'
    __v: 4
}

如何将其设置为仅返回{ name : 'blablabla' }

【问题讨论】:

  • 为什么不直接做res.send({ name: r.name })
  • 天哪!为什么我没有这样想!这对我有用。但是我可以通过mongoose 配置只返回name 吗?只是为了好奇

标签: javascript node.js mongodb mongoose


【解决方案1】:
// transform for sending as json
function omitPrivate(doc, obj) {
    delete obj.__v;
    delete obj.id;
    return obj;
}

// schema options
var options = { toJSON: { transform: omitPrivate } };

// schema
var schema = new Schema({
    name: { type: String, required: true },
}, options);

【讨论】:

    【解决方案2】:

    您可以为此编写方法:

    在您的用户架构中添加此方法: 使用这种方法,您可以控制返回给客户端的内容

    userSchema.methods.getPublicFields = function() {
      return {
        name: this.name
      };
    };
    

    并像这样使用它

    User.save({ name : userName })
         .then(r => {  
            res.send(r.getPublicFields);
         });
    

    【讨论】:

      猜你喜欢
      • 2017-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-02
      • 1970-01-01
      • 2016-06-17
      • 2021-02-18
      相关资源
      最近更新 更多