Categories
JavaScript Answers

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

Spread the love

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.

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 *