Express 如何在nodejs中将字符串转换为对象id

Express 如何在nodejs中将字符串转换为对象id,express,mongoose,Express,Mongoose,**帮我解决这个错误** 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' })

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

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' });
  }
试着这样做:

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

您得到的是什么错误?我没有从数据库中得到值,但在终端中它的显示类似于此应用程序侦听端口:3000 Mongodb运行GET/api/groups/5cf63667c3aa330eb53b4704/posts 200 5490.717 ms-28,在postman中它的显示posts值为null,如下所示:{“error”:false,“posts”:[]}我认为您的mongoose连接不起作用,显示您的PostModelImport mongoose,{Schema}来自“mongoose”;const GroupSchema=new Schema({name:{type:String,required:true,unique:true,minLength:[5',name必须是5个字符长'],},description:{type:String,required:true,minLength:[10',description必须是10个字符长'],},类别:{type:String,},posts:[{type:mongoose.Schema.Types.ObjectId,ref:'Post',},{timestamps:true});GroupSchema.statics.addPost=async函数(id,args){const Post=mongoose.model('Post');//我们将组id添加到Post组元素//最后这是Post const Post=wait new Post({…args,group:id})的作者;//我们在url//中找到了id为的组,并在posts元素const group=wait this.findByIdAndUpdate(id,{$push:{posts:post.id}});返回{post:wait post.save(),group,};};导出默认的mongoose.model('group',GroupSchema);