Home > Software design >  How can I pick values from one model and use them in another in nodejs using mongoose?
How can I pick values from one model and use them in another in nodejs using mongoose?

Time:11-10

Here, I have a model named User `

import mongoose from "mongoose";

const Schema = mongoose.Schema;

const userSchema = new Schema({
    name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true,
        unique: true
    },
    password: {
        type: String,
        required: true,
        minLength: 6
    },
    blogs:[{type:mongoose.Types.ObjectId,ref:"Blog",required:true}]
});
export default mongoose.model("User",userSchema);
//users

`

And I have a model named Blogs `

import mongoose from "mongoose";

const Schema = mongoose.Schema;

const blogSchema = new Schema({
    title:{
        type: String,
        required: true,
    },
    description:{
        type: String,
        required: true,
    },
    image:{
        type: String,
        required: true,
    },
    user:{
        type: mongoose.Types.ObjectId,
        ref:"User",
        required: true
    },
    name:{
        
    }
})
export default mongoose.model("Blog",blogSchema)

`

I want to fill the name in Blogs using the User model's name. `

import axios from 'axios'
import { useState } from 'react'
import { useEffect } from 'react'
import Blog from './Blog'
import { useSelector } from 'react-redux'
const Blogs = () =>{
    const isLoggedIn = useSelector(state=> state.isLoggedIn)
    const [blogs,setBlogs] = useState()
    const sendRequest = async() => {
        const resp = await axios.get('http://localhost:5000/api/blog')
        .catch(err=>console.log(err))
        const data = await resp.data
        return data
    }
    useEffect(()=>{
        sendRequest().then(data=>setBlogs(data.blogs))
    },[])
    console.log(blogs)
    return(
        <>
            {isLoggedIn && blogs && blogs.map((blog,index)=><Blog userName={blog.user.name} title={blog.title} description={blog.description} imageURL={blog.imageURL} />)}
        </>
    )
}
export default Blogs

` Here, I get error when I use blog.user.name I get errors as follows: Blogs.jsx:21 Uncaught TypeError: Cannot read properties of undefined (reading 'name') react_devtools_backend.js:4026 The above error occurred in the component: Consider adding an error boundary to your tree to customize error handling behavior.

How can I solve this problem?

CodePudding user response:

Hi I believe you are not using the populate method on the blog model when querying for the blog on the backend side. I have imagined you would have sth of this nature on the backend

const blogs = require('../models/blog')
blogs.find({}).populate('$user')

$user should be the name of the path you are trying to populate.

the populate method simply reads the user collection to obtain the user info, also you need to have stored the user '_id' when saving a blog, so the populate can work.

you can read about the populate method here https://mongoosejs.com/docs/populate.html.

  • Related