【问题标题】:Using Node.js and Mongoose what steps save a document and second document that references the first?使用 Node.js 和 Mongoose 哪些步骤可以保存引用第一个文档和第二个文档?
【发布时间】:2019-11-01 20:49:15
【问题描述】:

This brilliant answer by Soviut 解释了使用电子邮件验证来验证和激活新用户所需的逻辑步骤。

但是,使用 node.jsmongoose 我不确定保存文档以及引用第一个文档 ID 的第二个文档需要哪些步骤。

  1. 有没有办法同时保存两个文档?
  2. 是否需要保存第一个文档,然后使用findOne 找到它并将其 ID 复制到第二个文档中?
  3. 对于此类问题是否有最佳实践?

这里有 2 个示例架构,可以使这一点更清楚。

新用户:

const UserSchema = new mongoose.Schema({
    email: {
        type: String,
        required: true
    },
    yourName: {
        type: String,
        required: true
    },
    businessName: {
        type: String,
        required: true
    },
    password: {
        type: String,
        required: true
    },
    active: {
        type: Boolean,
        default: false
    }
});

用于验证的临时哈希:

const NewUserHash = new mongoose.Schema({
    randomHash: {
        type: String
    },
    // what is the best practice for getting the ID from a UserSchema document and saving it here?
    referenceToUser: {  
        type: String
    },
    createdAt: {
        type: Date,
        default: Date.now,
        expires: 7200
    }
});

【问题讨论】:

    标签: node.js mongoose


    【解决方案1】:

    我认为您正在尝试在用户验证电子邮件后验证用户,如果是这种情况,为什么没有两个模式,当用户第一次注册时,只需在用户发送后将数据添加到临时集合中验证成功请求只是从临时集合中取出数据并插入到永久集合中,并删除集合中的临时记录。

    是的,您可以使用 save 保存两个文档,但是一个接一个地保存,是的,如果您想链接,您必须先获取 id,我希望上述方法会更好。

    【讨论】:

      猜你喜欢
      • 2021-05-15
      • 2018-05-01
      • 2014-02-14
      • 2015-03-03
      • 1970-01-01
      • 2011-12-07
      • 2018-02-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多