node.js - 如何在 Mongoose 中自动创建必填字段

标签 node.js mongodb mongoose

我有一个看起来像这样的 Mongoose 模式:

var userSchema = new Schema({
    username: {type: String, required: true, index: {unique: true}},
    usernameCanonical: {type: String, required: true, index: {unique: true}}
});


userSchema.pre("save", function () {
    this.usernameCanonical = this.username.toLowerCase();
    return next();  
});

我希望只需输入用户名即可创建新用户,并让模型自动生成 usernameCanonical。

var user = new User({ 
    username: "EXAMPLE_USERNAME"
});
user.save()

当我尝试执行此操作时,我从 mongoose 收到验证错误,提示需要 usernameCanonical。

Path `usernameCanonical` is required.

问题似乎是预保存 Hook 在验证后被调用。我不想每次保存新用户时都必须手动添加规范用户名。我也不想从架构中删除 required 选项。

有没有办法让 Mongoose 模型自动生成必填字段?向架构中的 usernameCanonical 字段添加一个默认值似乎可以防止验证错误,但感觉就像一个 hack。

最佳答案

如 levi 所述,您应该使用 validate() Hook :

Save/Validate Hooks

根据您的代码检查这个工作示例:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const userSchema = new Schema({
  username: {type: String, required: true, index: {unique: true}},
  usernameCanonical: {type: String, required: true, index: {unique: true}}
});

userSchema.pre('validate', function () {
  if ((this.isNew || this.isModified) && this.username) {
    this.usernameCanonical = this.username.toLowerCase();
  }
});

const User = mongoose.model('user', userSchema);

mongoose.connect('mongodb://localhost:27017/uniqueTest')
  .then(() => {
    // create two users
    const user1 = new User({ 
      username: 'EXAMPLE_USERNAME-1'
    });
    const user2 = new User({ 
      username: 'EXAMPLE_USERNAME-2'
    });

    return Promise.all([
      user1.save(),
      user2.save()
    ]);
  })
  .then(() => {
    // update username
    return User.findOne({ username: 'EXAMPLE_USERNAME-1' })
      .then((user) => {
        user.username = 'EXAMPLE_USERNAME_UPDATED-1';
        return user.save();
      });
  })
  .then(() => mongoose.connection.close())
  .then(() => console.log('script finished successfully'))
  .catch((err) => {
    console.error(err);
    mongoose.connection.close()
      .then(() => process.exit(1));
  });

希望对您有所帮助。

关于node.js - 如何在 Mongoose 中自动创建必填字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24111760/

相关文章:

javascript - 异步 webpack 配置

javascript - JS Promise <Pending> 返回

javascript - 连接到 mlab 失败

mongodb - 更新 MongoDB 中的 _id 字段

node.js - 使用 Node 对 MongoDB 的 PATCH 方法

javascript - Mongoose 聚合成一个嵌套的 doc 获取计数并将新值附加到查询结果

node.js - 在 grunt/uglify 中结合 IIFE

javascript - Node.js 中的可变变量

r - 如何将数据从 mongodb 流式传输到 R?

javascript - 使用 Mongoose 模式导入 CSV