Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

366
Visualizações
How to get the id of a document before even saving it in mongoose?

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);

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);
  }
};

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.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You can generate your own id and save it

ObjectId id = new ObjectId()
about 4 years ago · Juan Pablo Isaza Relatório

0

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);
  }
};

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

Continue reading

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

Object Id's format and usage

about 4 years ago · Juan Pablo Isaza Relatório

0

You can just simply create a schema ovject like this:

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

This is from one of my projects, since the ObjectId from MongoDB is based on the operating machine and the time it is created, it doesn't need the database to generate the id. You can now access task._id to get your id without saving it.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda