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

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

问题描述

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

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

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

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

res.json(200,{user:user}); //如何排除_creator字段?
});
});

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

  {
name:'John',
age:45
}

有没有额外的发现请求可以进行mongoose?



PS :最好通过

解决方案

在模式级别处理这个的另一个方法是覆盖模型的JSON。

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

我遇到这个问题,寻找一种方法来排除从服务到客户端的json的密码哈希,而 select:false 破坏了我的verifyPassword函数,因为它根本没有从数据库中检索到值。


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?
   });
});

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:It's preferable to make it by

解决方案

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
}

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天全站免登陆