从数据库检索的文档的猫鼬验证

时间:2019-12-28 15:21:35

标签: mongoose

用户架构有两个字段:

const userSchema = new m.Schema({
  name: {
    type: String,
    required: true
  },
  nickname: {
    type: String,
    required: true,
    select: false
  }
});

当我手动创建文档并将“昵称”设置为undefined时,出现验证错误。但是,当我从数据库中选择一个用户文档时,尽管“昵称”字段未定义,但验证不会出错。为什么?

这是整个应用程序:

const m = require("mongoose");

const userSchema = new m.Schema({
  name: {
    type: String,
    required: true
  },
  nickname: {
    type: String,
    required: true,
    select: false
  }
});
const User = m.model("User", userSchema);

async function addUser() {
  const user = new User({
    name: "John",
    nickname: "Johnny"
  });
  try {
    await user.save();
  } catch (err) {
    console.log("err", err);
  }
}

async function checkUser() {
  const user1 = await User.findOne({ name: "John" });
  const user2 = new User({
    name: "John",
    nickname: undefined
  });

  const errors1 = user1.validateSync();
  console.log(errors1);
  const errors2 = user2.validateSync();
  console.log(errors2);
}

m.connect("mongodb://localhost:27017/testdb", {
  useNewUrlParser: true,
  useCreateIndex: true,
  useFindAndModify: false,
  useUnifiedTopology: true
}).then(async () => {
  console.log("MongoDb connection successfull");
  await addUser();
  await checkUser();
  console.log("finished");
});

0 个答案:

没有答案