6

我有以下架构。

var UserSchema = new mongoose.Schema({
  username: {
    type: String,
    unique: true,
    required: true
  },
  password: {
    type: String,
    required: true
  },
  test: {
    type: String, 
    default: 'hello world'
  }
});

UserSchema.pre('save', function(callback) {
  var user = this;
  this.test = undefined; // here unset test field which prevent to add in db 
});

module.exports = mongoose.model('User', UserSchema);

但是当我找到例如数据时

User.find(function(err, users) {
    if (err)
      res.send(err);

    res.json(users);
  });

它总是返回

[
    {
        _id: "56fa6c15a9383e7c0f2e4477",
        username: "abca",
        password: "$2a$05$GkssfHjoZnX8na/QMe79LOwutun1bv2o76gTQsIThnjOTW.sobD/2",
        __v: 0,
        test: "hello world"
    }
]

如何修改或添加任何特殊参数以获取没有test字段且查询没有任何更改的数据,比如说

User.find({}, '-test', function (err, users){

});

另外,我已经在模型中设置了默认值:test: "hello world" 但我不希望这个值出现在响应中。我也设置this.test = undefined;了,这应该意味着它会阻止将此默认值添加到数据库中,但是我仍然收到此响应。

4

3 回答 3

2
  1. 您希望该test属性保留在数据库中,只是不希望在查询时选择它:

您可以select在预查找挂钩中使用:

UserSchema.pre('find', function (next) {
    this.select({ test: false });
    next();
});

在查询挂钩(例如,与保存挂钩相反)中,this指的是您的查询对象。在保存挂钩中,它指的是正在保存的当前文档。

这个钩子只会对查询执行,而find不是查询。findByIdfindOne

或者

(见Hank Chiu的回答)

在架构中将选择标志设置为 false :

test: {
      type: String, 
      default: 'hello world',
      select: false,
}
  1. 您不希望该test属性保留在数据库中:

test从架构中删除该属性并添加一个test虚拟:

schema.virtual('test').get(function () {
    return 'hello world';
});

user.test将返回hello world

  1. 您希望 test 属性保留在数据库中,但返回不同的内容:

添加getter您的test定义:

test: {
    type: String, 
    default: 'hello world',
    get: function () {
        return 'hello guys';
    }
}

user.test将返回hello guys,但其真实值将保留在数据库中。

老错误答案:

您可以使用selectwhich 将模型属性的对象作为键和布尔值作为值:

User
    .find({})
    .select({
        test: false;
    })
    .exec(function (err, users) {
        // users won't have the test property
    });

于 2016-03-29T12:36:17.737 回答
2

将您的架构设置为

test: {
    type: String, 
    default: 'hello world',
    select: false
}

检查文档中的SchemaType#select

于 2016-03-29T14:57:24.813 回答
0

使用select函数作为你的例子,就像

User.find(/* condition */).select('username -_id -__v')

上面的代码将username只返回该字段

TL:博士

字段被写为带有空格分隔符的单个字符串,以排除字段添加-前缀,如-_idor -username

于 2019-01-08T20:05:07.173 回答