Reputation: 139
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 -
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 }) } })
Upvotes: 2
Views: 876
Reputation: 449
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)
Upvotes: 1
Reputation: 89
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.
Upvotes: 0