node.js - 如何限制在 find() 期间数据库中不存在的 Mongoose 默认值

标签 node.js mongoose mongoose-schema

我有以下架构。

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; 这应该意味着它阻止将此默认值添加到数据库中,但是我仍然收到此响应。

最佳答案

将您的架构设置为

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

检查 SchemaType#selectdocument .

关于node.js - 如何限制在 find() 期间数据库中不存在的 Mongoose 默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36284077/

相关文章:

javascript - 从 php 文件运行命令行程序

node.js - 在 Mongoose 中更新子文档

node.js - 我如何使用 `save` 与 mongoose 绑定(bind) `Q` 方法

mongodb - Mongoose 变量架构引用

javascript - 如何在侧面嵌套数组 Mongoose 中定义对象数组

javascript - Node.js 的正确继承

node.js - ObjectId 转换为 api 中的字符串,nodejs 到 reactjs

javascript - 为什么在某些情况下不会打印选项卡

mongoose - 将 Bluebird 用于 Mongoose promise 的正确方法是什么?

mongoose - 在 NestJS 中使用 Mongoose 鉴别器时出现 OverwriteModelError