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