Categories
JavaScript Answers

How to create Mongoose schema with array of Object IDs with JavaScript?

Spread the love

To create Mongoose schema with array of Object IDs with JavaScript, we use an array.

For instance, we write

const userSchema = mongoose.Schema({
  email: { type: String, required: true, unique: true },
  password: { type: String, required: true },
  name: {
    first: { type: String, required: true, trim: true },
    last: { type: String, required: true, trim: true },
  },
  phone: Number,
  lists: [listSchema],
  friends: [{ type: ObjectId, ref: "User" }],
  accessToken: { type: String },
});
exports.User = mongoose.model("User", userSchema);

to create the userSchema that has the friends field set to an array of object IDs.

We do that by setting it an array with an object with type set toi ObjectId.

ref is the collection that the IDs are referencing.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *