【问题标题】:Trying to delete a object reference in MongoDB with mongoose on NodeJS尝试使用 NodeJS 上的猫鼬删除 MongoDB 中的对象引用
【发布时间】:2021-07-06 06:54:40
【问题描述】:

我正在尝试删除在 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 文档中,它说它是一种执行预防措施的 prehook。这对我来说很有意义,因为根据代码,引用(auth)被删除,然后是对象(用户)。不幸的是,它并没有解决我的问题。有人可以帮帮我吗?

【问题讨论】:

    标签: node.js mongodb mongoose reference nosql


    【解决方案1】:

    您实际上如何为用户调用deleteOne()?你是在用户模型上调用它,还是在它的一个实例上调用它?

    这似乎与 pre hook options 参数的文档相关:

    [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()`
    });
    

    【讨论】:

    • 谁调用 .deleteOne 就是模型。我在调试时发现这个钩子从来没有被调用过。
    • 当你说模型时要清楚:这实际上是用户模型 - 导出为模型('User',UserSchema) - 或者这是一个模型实例 - 使用新用户创建( )?
    • 它不是模型的实例,它也是模型。
    猜你喜欢
    • 2015-09-15
    • 1970-01-01
    • 2021-06-01
    • 2017-07-05
    • 2017-03-28
    • 2020-09-11
    • 2016-04-11
    • 2021-11-21
    • 2014-05-12
    相关资源
    最近更新 更多