Categories
JavaScript Answers

How to create Mongoose schema with an array of object IDs with JavaScript?

Spread the love

Sometimes, we want to create Mongoose schema with an array of object IDs with JavaScript.

In this article, we’ll look at how to create Mongoose schema with an array of object IDs with JavaScript.

How to create Mongoose schema with an array of object IDs with JavaScript?

To create Mongoose schema with an array of object IDs with JavaScript, we can set schema property to an array of objects that specifies that the field is an array of object IDs.

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 that holds an array of object IDs by setting friends to [{ type: ObjectId, ref: "User" }].

We specifies that each friends entry references the object ID of a User.

Conclusion

To create Mongoose schema with an array of object IDs with JavaScript, we can set schema property to an array of objects that specifies that the field is an array of object IDs.

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 *