如何在Node.js中用Mongoose获取并更新指定电影场次的seats数组
Hey there! Let's work through your two technical needs one at a time—they're both pretty straightforward once you know the right Mongoose and JavaScript tricks.
First, let’s assume your Mongoose schema aligns with the structure you shared (where screens is an array of objects, each containing movieName and a movieTimings array). To update the seats array for a specific show, you’ll need to target the right screen (by movieName) and the right timing (I’ll assume your movieTimings entries have a time field—adjust the field name if yours is different).
Here’s a practical example using findOneAndUpdate (it’s handy because it returns the updated document for verification):
const mongoose = require('mongoose'); // Assume your model is named Theater const Theater = require('./models/theater'); async function updateMovieSeats(movieName, showTime, updatedSeats) { try { const updatedTheater = await Theater.findOneAndUpdate( { "screens.movieName": movieName, "screens.movieTimings.time": showTime }, { $set: { "screens.$[screen].movieTimings.$[timing].seats": updatedSeats } }, { arrayFilters: [ { "screen.movieName": movieName }, { "timing.time": showTime } ], new: true // Return the updated document instead of the original } ); if (!updatedTheater) { console.log('No theater/show found matching the criteria'); return; } console.log('Successfully updated seats:', updatedTheater); } catch (err) { console.error('Error updating seats:', err); } } // Usage example: Update seats for Avengers at 7:30 pm updateMovieSeats("Avengers", "7:30 pm", [1, 0, 1, 0, 1]);
Key notes:
- We use array filters (
arrayFilters) to precisely target the rightscreenandtimingin nested arrays—this prevents accidentally updating the wrong entry if multiple screens have the same movie name. - The
new: trueoption ensures we get the updated document back, which is useful for confirming changes. - If your
movieTimingsuses a different field name for the time (likeshowTimeinstead oftime), swap that out in the query and array filters.
First, let’s adjust your sample JSON to include the time field in movieTimings (since we need it to target the 7:30 pm show):
{ "_id": { "$oid": "5adc21bd19398524589381a9" }, "screens": [ { "_id": { "$oid": "5adc21bd19398524589381ad" }, "movieName": "Avengers", "movieTimings": [ { "time": "7:30 pm", "seats": [0, 0, 0, 1, 1] }, { "time": "9:45 pm", "seats": [0, 1, 0, 0, 1] } ] } ] }
Now, to extract the seats array for the 7:30 pm show, use JavaScript’s array methods to drill into the nested structure:
const theaterData = { /* Paste your full JSON object here */ }; function getMovieSeats(movieName, showTime) { // Find the screen for the target movie const targetScreen = theaterData.screens.find(screen => screen.movieName === movieName); if (!targetScreen) { console.log(`No screen found for movie: ${movieName}`); return null; } // Find the timing entry for the target show time const targetTiming = targetScreen.movieTimings.find(timing => timing.time === showTime); if (!targetTiming) { console.log(`No show time ${showTime} found for ${movieName}`); return null; } return targetTiming.seats; } // Usage example const avengers730Seats = getMovieSeats("Avengers", "7:30 pm"); console.log('Seats for Avengers 7:30 pm:', avengers730Seats);
Quick breakdown:
- First,
find()the screen that matches themovieNameto get the Avengers screen object. - Then,
find()the specific timing entry within that screen’smovieTimingsarray that matches "7:30 pm". - Finally, return the
seatsarray from that timing entry (or null if the movie/show time isn’t found).
内容的提问来源于stack exchange,提问作者Anurag Shinde

