2

I am using mongoose for defining schema. I have two schemas user and Userdetail. i want data from user in userdetail

I have below schema but i am not getting the output. i think the code is correct but not getting why there is no output...instead i am getting empty array.

const mongoose = require("mongoose")

const UserDetailSchema = mongoose.Schema({
    Phone : {
        type : Number
    },
    FirstName : {
        type : String
    },
    LastName : {
        type : String
    },
    productimage : {
        data : Buffer,
        contentType : String
    },
    IsDeleted:{
        type:Boolean,
        default:false
    },
    UserID : {
        type : String,
    },
    data : [{
        type: mongoose.Schema.Types.ObjectId,
        ref: "user"
    }],
},
{timestamps: true})

const UserDetail = new mongoose.model("userdetail",UserDetailSchema);

module.exports = UserDetail;

my user schema is,

    const mongoose = require("mongoose");

    const UserSchema = mongoose.Schema({
      email: {
        type: String,
        required: true
      },
      password: {
        type: String,
        required: true
      },
      IsDeleted:{
        type:Boolean
      },
    },
    {timestamps: true});

    module.exports = mongoose.model("user", UserSchema);

query is,

<pre>

router.get("/UserDetail",async (req,res)=>{
    try{
        const UsersData= await UserDetail.find();
        res.json(UsersData)
    }catch(e){
        res.status(500).json({ message: e.message })
    }
})

</pre>

Even though i am using only find, i must get the data with only id right?

Output is -

enter image description here

Any help would be appreciated

 router.patch("/UserDetail/:id",Auth,upload.single("productimage"),async(req,res)=>{

    try{


        const id = req.params.id;

        const updatedData = req.body;

        updatedData.productimage = {data: fs.readFileSync('upload/' + req.file.filename),
        contentType: 'image/png'};
        const options = { new: true };


        const result = await UserDetail.findOneAndUpdate(
            id, updatedData, options
        )

        res.send(result)
    }catch(e){
        res.status(500).json({ message: e.message })
    }
})

4
  • Can you share the query which you are writing ? Commented Oct 11, 2022 at 5:58
  • Sure Khalid...I have updated the que.. Commented Oct 11, 2022 at 6:29
  • Post you data stored in the db. Are there any ids in the array stored in the db? Commented Oct 11, 2022 at 10:16
  • Hi Marc, there is no array in db, this square bracket is there because i gave it in the model (please refer data values i have put in array in userdetail schema)....If i dont give square bracket, it shows nothing Commented Oct 11, 2022 at 13:22

2 Answers 2

1

Make changes in your model and then populate the data.

const mongoose = require("mongoose")

const UserDetailSchema = mongoose.Schema({
Phone : {
    type : Number
},
FirstName : {
    type : String
},
LastName : {
    type : String
},
productimage : {
    data : Buffer,
    contentType : String
},
IsDeleted:{
    type:Boolean,
    default:false
},
UserID : {
    type : String,
},
data : {
    type: mongoose.Schema.Types.ObjectId,
    ref: "user"
},
},
{timestamps: true})
}

populate query

let Model=//import your model here
let userdata=await Model.find().populate("data")
console.log(userdata)
Sign up to request clarification or add additional context in comments.

Comments

0

firstly you need a little change in userID in schema of userDetail.Please make it to UserID:{type : mongoose.Schema.Types.ObjectId}, as it will help you in future during aggregation and you can also remove data from your userDetail model as it will not store any data until you save it.And lastly try to run this aggregation query.

 const UsersData= await UserDetails.aggregate([
    {$lookup:
     {
     from: "users",
     localField: "userID",
     foreignField: "_id",
     as: "data" 
     }
    }])

In this way your respective details of users will be displayed in array of data.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.