Reputation: 1
I'm using Mongoose in my Node.js application. I have a Booking schema that references a Place schema using ObjectId. When I use the populate() method to retrieve the Place object, it only returns the ObjectId instead of the populated Place object
I’ve verified that the ref in my schema is correct and matches the model name. I have also verified that in the database i always have a place in the PlaceModel to correspond to the booking in the BookingModel.
Booking.js
const mongoose =require('mongoose');
const bookingSchema=new mongoose.Schema({
place: {type: mongoose.Schema.Types.ObjectId,required:true, ref:'Place'},
user: {type: mongoose.Schema.Types.ObjectId, ref:'User',required:true},
checkIn:{type:Date,required:true},
checkOut:{type:Date,required:true},
name:{type:String,required:true},
phone:{type:String,required:true},
guests:{type:Number,required:true},
price:{type:Number,required:true},
});
const BookingModel=mongoose.model('Booking',bookingSchema);
module.exports=BookingModel;
Place.js
const mongoose =require('mongoose');
const placeSchema=new mongoose.Schema({
owner: {type: mongoose.Schema.Types.ObjectId,ref: 'User'},
title:String,
address:String,
photos:[String],
description:String,
perks:[String],
extraInfo: String,
checkIn:Number,
checkOut:Number,
maxGuests: Number,
price:Number
});
const PlaceModel=mongoose.model('Place',placeSchema);
module.exports=PlaceModel;
index.js
app.get('/bookings', async (req, res) => {
try {
const userData = await getUserDataFromReq(req);
const bookings = await BookingModel.find({ user: userData.id }).populate("place").exec();
res.json(bookings);
} catch (error) {
console.error('Error in /bookings:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
});
it just returns the object id but im expecting an object in the 'place' field. Please help me through this problem. When I hit the /bookings
endpoint, the place
field in the returned data contains only the ObjectId
, like this:
[
{
"_id": "6487c4d3f6c0c8fa12345678",
"place": "6487c0f8f6c0c8fa12345677", // Just the ObjectId
"checkIn": "2024-11-28T00:00:00.000Z",
"checkOut": "2024-11-30T00:00:00.000Z",
"name": "John Doe",
"phone": "1234567890",
"guests": 2,
"price": 3000
}
]
Upvotes: 0
Views: 21