You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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.

1. Updating the seats array for a specific movie show in Node.js with Mongoose

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 right screen and timing in nested arrays—this prevents accidentally updating the wrong entry if multiple screens have the same movie name.
  • The new: true option ensures we get the updated document back, which is useful for confirming changes.
  • If your movieTimings uses a different field name for the time (like showTime instead of time), swap that out in the query and array filters.
2. Fetching the seats array for "Avengers" at 7:30 pm from your JSON structure

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 the movieName to get the Avengers screen object.
  • Then, find() the specific timing entry within that screen’s movieTimings array that matches "7:30 pm".
  • Finally, return the seats array from that timing entry (or null if the movie/show time isn’t found).

内容的提问来源于stack exchange,提问作者Anurag Shinde

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:49:55