小编waq*_*mil的帖子

如何限制在find()期间不存在于数据库中的猫鼬默认值

我有以下架构。

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);
Run Code Online (Sandbox Code Playgroud)

但是当我找到数据时

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

    res.json(users);
  });
Run Code Online (Sandbox Code Playgroud)

它总是返回

[
    {
        _id: "56fa6c15a9383e7c0f2e4477",
        username: "abca",
        password: "$2a$05$GkssfHjoZnX8na/QMe79LOwutun1bv2o76gTQsIThnjOTW.sobD/2",
        __v: 0,
        test: "hello world" …
Run Code Online (Sandbox Code Playgroud)

mongoose node.js mongoose-schema

5
推荐指数
1
解决办法
2036
查看次数

标签 统计

mongoose ×1

mongoose-schema ×1

node.js ×1