如何在创建猫鼬模型时保存记录?

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

我正在使用mongoose在Node.js / Express上的Web应用程序上工作,并且应该在数据库中内置一个管理员用户,因此我每次发布时都不会被迫用curl或其他方式创建它因此,我想知道是否有类似oncreate的钩子仅在创建时才用记录初始化数据库。

node.js express mongoose
1个回答
0
投票

可以在Web服务初始化期间插入管理员帐户,以使即使多次执行查询,也只会创建一个带有管理员用户名的文档。可以使用upsert查询创建文档:

await administratorModel.update({
  // These are the document properties for the admin model
  username: "admin"
}, {
  // This is the filter that mongoose will query if is satisfied in the db
  username: “admin”
}, { 
  // If the document didn't exist in the db, 'upsert' tells mongoose to insert it 
  upsert: true 
})

猫鼬文档:Model.update()

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