简体   繁体   中英

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.

You can generate your own id and save it

ObjectId id = new ObjectId()

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM