Home > other >  Get the data inside request array inside of a schema
Get the data inside request array inside of a schema

Time:11-15

How can I create a route to get postedby data which is inside requests array. The request array is inside of a Post schema

const mongoose = require("mongoose")
const {ObjectId} = mongoose.Schema.Types

const postSchema = new mongoose.Schema({
    name:{
        type: String,
        required: true
    },
    jobtitle:{
        type: String,
        required: true
    },
    requests:[{
        text: String,
        postedby:{type: ObjectId, ref: "User"}
    }],
    postedby:{
        type: ObjectId,
        ref: "User"
    }
})

mongoose.model("Post", postSchema)

I tried this but I was getting another postedby

router.get("/acceptedpost",requireLogin,(req,res)=>{
    Post.find({postedby:req.user._id})
    .populate("postedby","_id name")
    .then(accpost => {
        res.json({accpost})
    })
    .catch(err => {
        console.log(err)
    })
})

CodePudding user response:

If you want to match the req.user._id against the requests array, you can simply do:

Post.find({"requests.postedby": req.user._id})
    .populate("postedby", "requests.postedby")
    .then(accpost => {
        res.json({accpost})
    })
    .catch(err => {
        console.log(err)
    })
  • Related