Is there a way to connect two models in mern and access user id of other model

33 views Asked by At

I am getting this error while adding a new note to MongoDB Atlas . I have two models note and User. I'm getting an error that user is not recognized or undefined id . Can anyone tell me what to do to resolve error and get a particular note added?

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
     }
    }

}

I tried adding a note(title ,description and tag) connected to a different model for user to get the id of user at model note like this:

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

but nothing works.

1

There are 1 answers

0
SerhiiL On

To solve this problem, first you need to convert user.id to ObjectId and after that you need to perform operations.

import { ObjectId } from 'bson';

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

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