Search code examples
mongoose-schema

How to set an ObjectId in Mongoose?


I have a flights model file:

const flightsSchema = new Schema({
  departureDate: {
    type: String,
    required: true,
  },
  returnDate: {
    type: String,
  },
});

Then I have a trips model file:

const tripsSchema = new Schema({
  email: {
    type: String,
    required: true,
    lowercase: true,
    unique: true,
  },
  flight: {
    type: mongoose.Schema.Types.ObjectId,
    ref: Flights,
    required: true,
  },
});

Finally, I have an expressJS route that tries to create a new Trip:

  const testData = {
    email: "email123@gmail.com",
    flight: {
      departureDate: "today",
      returnDate: "tomorrow",
    },
  };
    
  const trip = new Trips(testData);
  try {
    await trip.save();
    return res.status(200).json({
      success: true,
    });
  } catch (err) {
    console.log(err);
  }
    });

However, when I visit the route, I get the following error:

Error: Argument passed in must be a single String of 12 bytes or a
 string of 24 hex characters
          at new ObjectID

Why is this error coming?


Solution

  • First create the Flight document and save it. Then save the _id of the Flight document in the Trip document.

    const flightData = {
      departureDate: "today",
      returnDate: "tomorrow",
    };
    
    try {
      // Save flight data
      const flight = new Flights(flightData);
      const flightObject = await flight.save();
    
      // Save trip data
      const trip = new Trips({
        email: "email123@gmail.com",
        flight: flightObject._id
      });
      await trip.save();
      return res.status(200).json({
        success: true,
      });
    } catch (err) {
      console.log(err);
    }
    });