首页 > 解决方案 > 如何使用 async/await 语法填充我的模型?

问题描述

我读过很多类似的帖子,大部分例子都是回调。我正在尝试创建评论并将其添加到我的帖子中。

const Post = require('./models/Post');
const Comment = require('./models/Comment');

const newLocal = 'mongodb://localhost/postdb';
mongoose.connect(newLocal, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  }).then(() => console.log('Successfully connect to MongoDB.'))
  .catch((err) => console.error('Connection error', err));

  async function readP() {
    try {
      const comment = await Comment.create(
        {title : 'Boa tarde', 
        body: 'Adriana bonita',
        postedBy : mongoose.Types.ObjectId("5f96e440f47c1d211e84d712")
      });
       const post = await Post.findOne({ title: 'BJohnson'}).
       populate( {path : 'comment'},
       );
      } catch (err) {
        console.log(err);
      }
  }

  readP();

后模式

const PostSchema = new mongoose.Schema({
  title: String,
  body: String,
  createdAt: {
    type: Date,
    default: Date.now,
  },
  postedBy: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
  },
  comments: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Comment',
  }] 
});

B约翰逊邮报

{ "_id" : ObjectId("5fa13e1523e71045227bf74d"), "comments" : [ ObjectId("5fa13e1523e71045227bf74c") ]

评论已创建,但未添加到帖子。如何以适当的方式指定路径?

标签: node.jsmongoose

解决方案


您可以使用findOneAndUpdate(). 在您的情况下,它将找到 Post 并使用 commentId 更新 Post。我假设您的 Post Schema 看起来与此有些相似 -

const mongoose = require('mongoose')

const PostSchema = new mongoose.Schema({
  title: String,
  body: String,
  createdAt: {
    type: Date,
    default: Date.now,
  },
  postedBy: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
  },
  comments: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Comment',
  }]
});

module.exports = PostSchema
const Post = require('./models/Post');
const Comment = require('./models/Comment');

const newLocal = 'mongodb://localhost/postdb';
mongoose.connect(newLocal, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  }).then(() => console.log('Successfully connect to MongoDB.'))
  .catch((err) => console.error('Connection error', err));

  async function readP() {
    try {
      const comment = await Comment.create(
        {title : 'Boa tarde',
        body: 'Adriana bonita',
        postedBy : mongoose.Types.ObjectId("5f96e440f47c1d211e84d712")
      });
      const post = await Post.findOne({ title: 'BJohnson'})

      const commentIds = post.comments || [] // get all the comment Id's of the post
      commentIds.push(comment.id) // Push the new comment id to existing comment Id's
      
      const updatedPost = await Post.findOneAndUpdate({ title: 'BJohnson'}, {comments: commentIds}).populate({path : 'comment'});
      } catch (err) {
        console.log(err);
      }
  }

  readP();

推荐阅读