如何在mongoose中保存文档之前获取文档的id?

yftpprvb  于 2023-10-19  发布在  Go
关注(0)|答案(4)|浏览(162)

我有一个简单的控制器,可以为用户创建一个帖子。另一个架构与之链接。当我尝试创建一个新的post时,我需要获取post的id,这样我就可以将其他模式链接到它。
下面是schema:

  1. const mongoose = require("mongoose");
  2. const User = require("./User");
  3. const View = require("./View");
  4. const ArticleSchema = new mongoose.Schema({
  5. title: {
  6. type: String,
  7. required: true,
  8. trim: true,
  9. },
  10. body: {
  11. type: String,
  12. required: true,
  13. },
  14. status: {
  15. type: String,
  16. default: "public",
  17. enum: ["public", "private"],
  18. },
  19. user: {
  20. type: mongoose.Schema.Types.ObjectId,
  21. ref: "User",
  22. },
  23. views: {
  24. type: mongoose.Schema.Types.ObjectId,
  25. ref: "View",
  26. },
  27. createdAt: {
  28. type: Date,
  29. default: Date.now,
  30. },
  31. });
  32. module.exports = mongoose.model("Article", ArticleSchema);

当我想链接user字段时,这是很好的,因为我已经将其存储在内存中。
但是view字段需要该特定文档的postId。如果不先创建文档,我就得不到它。
我的创建后控制器:

  1. module.exports.createArticleController = async function (req, res) {
  2. try {
  3. req.body.user = req.User._id;
  4. const article = await Article.create(req.body).exec()
  5. res.redirect(`/${article.title}/${article._id}`);
  6. } catch (e) {
  7. console.error(e);
  8. }
  9. };

所以我的问题是
我如何在执行model.create()的过程中获得id,以便我可以将视图链接到该id。也许有些东西使用 *this * 运算符
我不想在创建后使用更新。

wmtdaxz3

wmtdaxz31#

您可以在创建Model示例后立即获取对象ID,或者创建自己的对象ID并保存它们。
我是这样做到的:

  1. module.exports.createArticleController = async function (req, res) {
  2. try {
  3. const instance = new Article();
  4. instance.title = req.body.title;
  5. instance.body = req.body.body;
  6. instance.status = req.body.status;
  7. instance.user = req.User._id;
  8. instance.views = instance._id;
  9. const article = await instance.save();
  10. if (article) {
  11. res.redirect(`/${article.title}/${article._id}`);
  12. }
  13. } catch (e) {
  14. console.error(e);
  15. }
  16. };

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

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

继续阅读
How do I get the object Id in mongoose after saving it.
Object Id's format and usage

展开查看全部
7uzetpgm

7uzetpgm2#

您可以生成自己的id并保存它

  1. ObjectId id = new ObjectId()
c6ubokkw

c6ubokkw3#

你可以像这样简单地创建一个schema对象:

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

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

kdfy810k

kdfy810k4#

  1. interface NotificationModel extends mongoose.Model<NotificationDoc> {
  2. build(attrs: NotificationAttrs): NotificationDoc;
  3. }
  4. const notificationSchema = new mongoose.Schema(
  5. {
  6. sk: {
  7. type: Number,
  8. },
  9. createdAt: {
  10. type: mongoose.Schema.Types.Date,
  11. },
  12. },
  13. {
  14. shardKey: { sk: 1, createdAt: 1 },
  15. toJSON: {
  16. transform(doc, ret) {
  17. ret.id = ret._id;
  18. delete ret._id;
  19. },
  20. },
  21. }
  22. );
  23. notificationSchema.statics.build = (attrs: NotificationAttrs) => {
  24. return new Notification(attrs);
  25. };
  26. const Notification = mongoose.model<NotificationDoc, NotificationModel>(
  27. 'Notification',
  28. notificationSchema
  29. );
  30. export { Notification };

现在您可以先构建然后保存

  1. const notification: NotificationAttrs = {
  2. sk: user,sk,
  3. createdAt: new Date(),
  4. };
  5. const notificationDoc = Notification.build(notification);
  6. console.log(notificationDoc.id)
  7. await notificationDoc.save();
  8. ```
展开查看全部

相关问题