How to create a schema from a preexisting collection with Mongoose?

Sometimes, we want to create a schema from a preexisting collection with Mongoose.

In this article, we’ll look at how to create a schema from a preexisting collection with Mongoose.

How to create a schema from a preexisting collection with Mongoose?

To create a schema from a preexisting collection with Mongoose, we can set the collection option when we’re creating the schema.

For instance, we write

new Schema({
  url: String,
  text: String,
  id: Number
}, {
  collection: 'question'
});

to call the Schema constructor with an object with the properties of the documents and another object that specifies the collection` that the schema references.

We reference the question collection with the schema we created.

Conclusion

To create a schema from a preexisting collection with Mongoose, we can set the collection option when we’re creating the schema.