如何在 mongodb 的 Nodejs 详细信息中添加 findone 进行名称验证

问题描述 投票:0回答:1

你们中的任何人都可以解决这个问题,避免名称重复,并在 postman api 上执行,代码附在下面

*employeemodel.jsenter image description here

*employeecontroller.jsenter image description here

*routes.jsenter image description here

node.js angular mongodb express mean-stack
1个回答
0
投票

我不确定我是否正确理解了你的问题。但是,如果您想防止 EmployeeModel 中出现重名,您可以使用 Unique Indexes,就像

unique: true
中的
employeemodel.js
一样:

const employeeSchema = new Schema({
  name: {
    type: String,
    required: true,
    unique: true
  }
})

使用现有名称保存新模型时,在

employeeController.js
上的
await employeeModelData.save()
中,您将收到错误,这将通过您的 try-catch 捕获。

如果您需要更多信息和示例,可以查看:了解 Mongoose 中的唯一性

© www.soinside.com 2019 - 2024. All rights reserved.