有没有办法在mern中连接两个模型并访问其他模型的用户id

问题描述 投票:0回答:1

我在向 MongoDB Atlas 添加新注释时收到此错误。我有两个模型 note 和 User。我收到错误消息,指出用户无法识别或未定义 id 。谁能告诉我如何解决错误并添加特定注释?

router.post('/addnotes',authenticate,async (req,res)=>{
     
    const {title , description,  tags,}=req.body;                                              

    if(!title ||!description || !tags) {      //to tell user in case anything missing
      return res.status(422).json({message:"fill properly"});
    }
   
    try{
      const note = new  Notes({title,description,tags,user:req.user.id})
    
      await note.save();
      return res.status(201).json({message:" New Note saved Successfully"});

    } catch(error){
      if (!req.user) {
        console.log("no user");
        res.send("no user");
     } else if (!req.user.id) {
          console.log("no id ");
     } else {
       res.send("you are in");
       // The user is logged in and has an id
     }
    }

}

我尝试添加一个连接到不同模型的注释(标题、描述和标签),以便用户在模型注释中获取用户 ID,如下所示:

const notesSchema = new mongoose.Schema({
  user:{
    type: mongoose.Schema.Types.ObjectId,
    ref:'User'
  },
  title: String,
  description: String,
  tags:{
    type: String,
    default : "General"
  },
  date:{
    type :Date,
    default:Date.now
  },  
});

但没有任何作用。

node.js mongodb mongoose model mern
1个回答
0
投票

要解决这个问题,首先需要将user.id转换为ObjectId,然后进行操作。

import { ObjectId } from 'bson';

const userId = new ObjectId(req.user.id);

try{
 const note = new  Notes({title,description,tags,user:userId})
...

© www.soinside.com 2019 - 2024. All rights reserved.