【问题标题】:How to get the id of a document before even saving it in mongoose?如何在将文档保存在猫鼬之前获取文档的 ID?
【发布时间】:2022-01-10 20:33:27
【问题描述】:

我有一个简单的控制器,可以为用户创建帖子。另一个模式链接到它。当我尝试创建新帖子时,我需要获取帖子的 ID,以便我可以将其他架构链接到它。

这是架构:

const mongoose = require("mongoose");
const User = require("./User");
const View = require("./View");

const ArticleSchema = new mongoose.Schema({
  title: {
    type: String,
    required: true,
    trim: true,
  },
  body: {
    type: String,
    required: true,
  },
  status: {
    type: String,
    default: "public",
    enum: ["public", "private"],
  },
  user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "User",
  },
  views: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "View",
  },
  createdAt: {
    type: Date,
    default: Date.now,
  },
});

module.exports = mongoose.model("Article", ArticleSchema);

当我想链接 user 字段时很好,因为我已将其存储在内存中。

view 字段需要该特定文档的 postId。如果不先创建文档,我将无法获得它。

我的创建后控制器:

module.exports.createArticleController = async function (req, res) {
  try {
    req.body.user = req.User._id;
    const article = await Article.create(req.body).exec()
    res.redirect(`/${article.title}/${article._id}`);
  } catch (e) {
    console.error(e);
  }
};

所以我的问题是,

如何在执行 model.create() 的过程中获取 id,以便我可以将视图链接到该 id。也许使用 this 运算符

我不想在创建后使用更新。

【问题讨论】:

    标签: javascript node.js mongoose mongodb-query mongoose-schema


    【解决方案1】:

    你可以生成自己的id并保存

    ObjectId id = new ObjectId()
    

    【讨论】:

    • 请详细说明您的回答。添加修改后的代码示例和说明。
    【解决方案2】:

    您可以在创建模型实例后立即获取对象 ID,或者创建自己的对象 ID 并保存。

    我是这样实现的:

    module.exports.createArticleController = async function (req, res) {
      try {
        const instance = new Article();
    
        instance.title = req.body.title;
        instance.body = req.body.body;
        instance.status = req.body.status;
        instance.user = req.User._id;
        instance.views = instance._id;
    
        const article = await instance.save();
    
        if (article) {
          res.redirect(`/${article.title}/${article._id}`);
        }
      } catch (e) {
        console.error(e);
      }
    };

    或者您可以创建它们并将其保存到数据库中。

    var mongoose = require('mongoose');
    var myId = mongoose.Types.ObjectId();
    
    const instance = new YourModel({_id: myId})
    
    //use it

    继续阅读

    How do I get the object Id in mongoose after saving it.

    Object Id's format and usage

    【讨论】:

      【解决方案3】:

      您可以像这样简单地创建一个模式对象:

      const task: TaskDocument = new this.taskSchema({ ...createTaskDto })
      

      这是我的一个项目,因为 MongoDB 的 ObjectId 是基于操作系统和创建时间的,所以不需要数据库来生成 id。 您现在可以访问 task._id 来获取您的 id 而无需保存它。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-06-17
        • 2017-12-05
        • 1970-01-01
        • 2016-04-20
        • 1970-01-01
        • 2017-11-24
        • 1970-01-01
        • 2016-01-24
        相关资源
        最近更新 更多