尝试使用 NodeJS 上的 mongoose 删除 MongoDB 中的对象引用
Trying to delete a object reference in MongoDB with mongoose on NodeJS
我正在尝试删除在 MongoDB 数据库中创建的引用。为了更好地理解,我有两个模型,即用户和身份验证。每次我创建用户时,都会创建身份验证作为参考,将其值保存在电子邮件字段中。
一切正常,问题是当我尝试删除用户时,引用仍然在同一个地方。
这些是我的模型、用户和身份验证:
import { Schema, model } from 'mongoose'
const stringRequired = {
type: String,
trim: true,
required: true
}
const stringUnique = {
...stringRequired,
unique: true
}
const UserSchema = new Schema({
name: stringRequired,
username: stringUnique,
email: stringUnique,
}, { timestamps: true });
const userModel = model('User', UserSchema)
const AuthSchema = new Schema({
email: { type: Schema.Types.ObjectId, ref: 'User' },
salt: stringRequired,
hash: stringRequired,
}, { timestamps: true })
const authModel = model('Auth', AuthSchema)
export { userModel, authModel }
在网上搜索我遇到了一个假设的解决方案:
UserSchema.pre('deleteOne', function () {
const user = this
user.model('AuthSchema').deleteOne({ email: user._id})
})
在 mongoose 文档中说它是一种执行预防措施的预挂钩。这对我来说很有意义,因为根据代码,引用 (auth) 被删除,然后是对象 (user)。不幸的是,它不能解决我的问题。有人可以帮助我吗?
您实际上是如何为用户调用 deleteOne()
的?您是在用户模型上调用它,还是在它的实例上调用它?
根据预挂钩选项参数的文档,这似乎是相关的:
[options.document] «Boolean» 如果 name 是文档和查询中间件的挂钩,则在文档中间件上将 运行 设置为 true。例如,将 options.document 设置为 true 以将此挂钩应用于 Document#deleteOne() 而不是 Query#deleteOne()。
https://mongoosejs.com/docs/api.html#schema_Schema-pre
他们进一步提供了一个例子:
toySchema.pre('deleteOne', function() {
// Runs when you call `Toy.deleteOne()`
});
toySchema.pre('deleteOne', { document: true }, function() {
// Runs when you call `doc.deleteOne()`
});
我正在尝试删除在 MongoDB 数据库中创建的引用。为了更好地理解,我有两个模型,即用户和身份验证。每次我创建用户时,都会创建身份验证作为参考,将其值保存在电子邮件字段中。 一切正常,问题是当我尝试删除用户时,引用仍然在同一个地方。
这些是我的模型、用户和身份验证:
import { Schema, model } from 'mongoose'
const stringRequired = {
type: String,
trim: true,
required: true
}
const stringUnique = {
...stringRequired,
unique: true
}
const UserSchema = new Schema({
name: stringRequired,
username: stringUnique,
email: stringUnique,
}, { timestamps: true });
const userModel = model('User', UserSchema)
const AuthSchema = new Schema({
email: { type: Schema.Types.ObjectId, ref: 'User' },
salt: stringRequired,
hash: stringRequired,
}, { timestamps: true })
const authModel = model('Auth', AuthSchema)
export { userModel, authModel }
在网上搜索我遇到了一个假设的解决方案:
UserSchema.pre('deleteOne', function () {
const user = this
user.model('AuthSchema').deleteOne({ email: user._id})
})
在 mongoose 文档中说它是一种执行预防措施的预挂钩。这对我来说很有意义,因为根据代码,引用 (auth) 被删除,然后是对象 (user)。不幸的是,它不能解决我的问题。有人可以帮助我吗?
您实际上是如何为用户调用 deleteOne()
的?您是在用户模型上调用它,还是在它的实例上调用它?
根据预挂钩选项参数的文档,这似乎是相关的:
[options.document] «Boolean» 如果 name 是文档和查询中间件的挂钩,则在文档中间件上将 运行 设置为 true。例如,将 options.document 设置为 true 以将此挂钩应用于 Document#deleteOne() 而不是 Query#deleteOne()。
https://mongoosejs.com/docs/api.html#schema_Schema-pre
他们进一步提供了一个例子:
toySchema.pre('deleteOne', function() {
// Runs when you call `Toy.deleteOne()`
});
toySchema.pre('deleteOne', { document: true }, function() {
// Runs when you call `doc.deleteOne()`
});