【问题标题】:How to transform string to object id in nodejs如何在nodejs中将字符串转换为对象ID
【发布时间】:2019-06-06 15:38:11
【问题描述】:

**帮我解决这个错误**

try {
    return res.status(200).json({
      error: false,
     Posts: await Post.find({ group: groupId }).populate('group', 'name'),
    });
  } catch (e) {
    return res.status(400).json({ error: true, message: 'Cannot fetch post' });
  }

【问题讨论】:

  • 你遇到了什么错误?
  • 我没有从数据库中获取价值,但在终端中显示如下应用程序监听端口:3000 Mongodb running GET /api/groups/5cf63667c3aa330eb53b4704/posts 200 5490.717 ms - 28
  • 并在邮递员中显示帖子值 null 如下:{“错误”:假​​,“帖子”:[]}

标签: express mongoose


【解决方案1】:

试试这个方法:

try {

Post.find({ group: groupId }).populate('group', 'name').exec((err,posts)=>{
    if(err){
       return res.status(500).json({ error: true, message: 'Internal Server Error' });
    } 

    if(posts){
        return res.status(200).json({
        error: false,
        Posts: posts
       });
     }else{
       return res.status(400).json({ error: true, message: 'Cannot fetch post' });
     }
});

  } catch (e) {
   return res.status(500).json({ error: true, message: 'Internal Server Error' });
 }

【讨论】:

  • 我认为你的猫鼬连接不工作,显示你的帖子模型
  • 从“猫鼬”导入猫鼬,{ Schema }; const GroupSchema = new Schema({ name: { type: String, required: true, unique: true, minLength: [5, 'Name must be 5 characters long'], }, description: { type: String, required: true, minLength: [10, 'Description must be 10 characters long'], }, category: { type: String, }, posts: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Post', }], } , { 时间戳: true });
  • GroupSchema.statics.addPost = async function (id, args) { const Post = mongoose.model('Post'); // 我们将组 id 添加到帖子组元素 // 最后这是帖子的作者 const post = await new Post({ ...args, group: id }); // 我们在 url 中找到了 id 提供的组 // 然后我们将帖子 id 推送到帖子元素中 const group = await this.findByIdAndUpdate(id, { $push: { posts: post.id } });返回{帖子:等待post.save(),组,}; }; export default mongoose.model('Group', GroupSchema);
猜你喜欢
  • 2020-08-13
  • 1970-01-01
  • 2019-05-25
  • 1970-01-01
  • 1970-01-01
  • 2021-02-03
  • 2018-07-19
  • 2019-07-07
相关资源
最近更新 更多