I've seen a few similar questions to this on here but none of the solutions seem to work. I am creating a table planner for my wedding and I'm trying to perform a query to return all of the dinner tables (Top Table, Table One, Table Two, etc) with a list of the guests assigned to those tables. I have the following schemas:
const guestSchema = new mongoose.Schema({ firstname: { type: String, required: 'Please provide the first name of the guest', trim: true }, surname: { type: String, required: 'Please provide the surname of the guest', trim: true }, attending: { type: String, default: 'Awaiting RSVP' }, menu: { type: String, default: 'Awaiting RSVP' }, allergies: { type: String, default: 'Awaiting RSVP' }, table: [{ type: mongoose.Schema.ObjectId, ref: 'Table', }] }); const tableSchema = new mongoose.Schema({ name: { type: String, required: 'Please provide the name of the table', trim: true }, capacity: { type: Number, required: 'Please provide the capacity of the table', }, guests: [{ type: mongoose.Schema.ObjectId, ref: 'Guest', }] });
In my guestsController.js I have then set up an API endpoint like so:
exports.getTableGuests = async (req, res) => { const guests = await Table.find().populate({path: 'guests', select: 'firstname surname', model: 'Guest'}); res.json(guests); };
where guests is the name of the foreign field within the Table model. In the returned JSON I do get a guests array but its empty.
Any ideas?
2 Answers
Answers 1
Use mongoose.Schema.Types.ObjectId
instead of mongoose.Schema.ObjectId
. That will solve the problem.
Answers 2
Ok I spotted the problem myself. The problem was that I had a load-data.js script that I was running to load in guests and tables from JSON files. The JSON data for the tables contained guest ids for guests that were currently in the database at the time of the load. But when the script runs it deletes all the guests and generates new ids for them so the ids weren't matching up with those in the table collection.
To fix this I separated the loading of guests and tables so that I could then manually add in the correct ids. I will now create an interface within my app to create these relationships to remove the manual process.
0 comments:
Post a Comment