Home > Enterprise >  How to get the id of a document before even saving it in mongoose?
How to get the id of a document before even saving it in mongoose?

Time:12-06

I have a simple controller that creates a post for a user. Another schema is linked to it. When I try to create a new post, I need to get the id of the post so that I can link other schema to it.

Here is the schema:

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);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

It is fine when I want to link the user field because I have that stored in memory.

But the view field requires postId of that particular document. And I can't get it without first creating the document.

My create post controller:

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);
  }
};
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

So my question is,

How can i get the id in the process of executing the model.create() so that i can link the view to that id. Maybe something using the this operator

I don't want to use update after create.

CodePudding user response:

You can generate your own id and save it

ObjectId id = new ObjectId()

CodePudding user response:

You can get object Id's right after creating an instance of Model or create your own object id's and save them.

Here's how i achieved it:

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);
  }
};
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Or you can create them and save it to the db.

var mongoose = require('mongoose');
var myId = mongoose.Types.ObjectId();

const instance = new YourModel({_id: myId})

//use it
<iframe name="sif4" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Continue reading

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

Object Id's format and usage

  • Related