如何从文档中排除某些字段 [英] How to exclude some fields from the document

查看:39
本文介绍了如何从文档中排除某些字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下简单的shema:

I have the following simple shema:

 var userSchema = new Schema({
    name : String,
   age: Number,
   _creator: Schema.ObjectId
  });

  var User = mongoose.model('User',userSchema);

我想做的是创建新文档并返回给客户端,但我想从其中排除创建者"字段:

What I want to do is create the new document and return to client, but I want to exclude the 'creator' field from one:

app.post('/example.json', function (req, res) {
   var user = new User({name: 'John', age: 45, _creator: 'some ObjectId'});
   user.save(function (err) {
      if (err) throw err;

      res.json(200, {user: user});     // how to exclude the _creator field?
   });
});

最后我想发送没有 _creator 字段的新创建的用户:

At the end I want to send the new created user without _creator field:

{
   name: 'John',
   age: 45
} 

是否可以在没有额外查找请求的情况下向猫鼬发出请求?

Is it possible to make without extra find request to mongoose?

P.S:最好在

推荐答案

在架构级别处理此问题的另一种方法是覆盖模型的 toJSON.

Another way to handle this on the schema level is to override toJSON for the model.

UserSchema.methods.toJSON = function() {
  var obj = this.toObject()
  delete obj.passwordHash
  return obj
}

我遇到了这个问题,正在寻找一种方法来从我提供给客户端的 json 中排除密码哈希,而 select: false 破坏了我的 verifyPassword 函数,因为它没有从数据库.

I came across this question looking for a way to exclude password hash from the json i served to the client, and select: false broke my verifyPassword function because it didn't retrieve the value from the database at all.

这篇关于如何从文档中排除某些字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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