Mongoose

  1. Mongoose Introduction

    Mongoose is a package that uses promises and async/await. Mongoose is an ORM (object relational mapper) or ODM (object data mapping), which is specific to Mongodb. It encapsulates functions such as CRUD, provides new interfaces, and is more convenient.

    There are similar packages for other databases like the sequelize package for databases like mySQL. In actual development, there is rarely direct interaction with the database, and the ORM library is used for CRUD. If you pursue the ultimate efficiency, you may write an ORM library by hand, because the popular ORM library is aimed at most users.


    Data is fetched from the database to the server, and it will go through the Mongoose layer in the middle. Mongoose will convert json raw data into Object in JS, so that we can operate Mongoose objects by operating on Object. There’s some performance loss here, and sometimes you don’t need to convert, you need to optimize yourself.


  1. Keywords in Mongoose

    Schema, Model, Document are keywords in Mongoose.

    • schema is the data design diagram, the fields that list the data, etc.

    • Model (corresponding to collection in Mongodb) is to create a model through schema drawings. One use is to generate a document (create a model instance), which needs to be passed in the fields defined in the schema.

      Another use of Model is collection operations on data, you can add documents, search the entire collection, etc.

    • document is slightly different from document in Mongodb, it is similar to document in Mongodb. It is a JS object and is created by Mongoose. Therefore, it is not only the data in bson format in the database, but also supports the API in Mongoose to process data more conveniently.

    1
    2
    3
    const schema = new mongoose.Schema({name: String});
    const Model = mongoose.model('Model', schema);
    const document = new Model({name: 'document'})


  1. Install Mongoose

    npm i mongoose

    Because Mongoose is used to create a model for a resource, it should be placed in the models folder under src.


  1. Processing of pictures in the database

    There are generally two ways to process images.

    1. Save the base64 image directly to the database. In this case, if the image is large, each read will be slower. Not recommended.
    2. The database will not store data directly, but first upload the image to the image bed (such as github, AWS S3), and the platform will return the url and then store it in the database.

Share