简体   繁体   中英

Creating database model with Mongoose

I have a node.js app that is essentially a sketchpad and currently I'm working on a feature to enable to save all of the sketches they've drawn during a "session" to a database so they can pick back up at a later time where they left off. I'm using a MongoDB database that I'm connecting to via the Mongoose ORM.

The server is started up in the file main.js which is currently where I'm opening the connection to the DB; however, the code for the saving of sketch data (which is currently just being saved to a JSON file on the server) is in a separate file. Based on this tutorial it seems that the code for the creation of models for a document are to go inside of a callback function that is run once the connection is open. But given that the logic for saving sketches in the app is in a different file from where the connection is being opened and since it says here that model instances aren't created/removed until the connection is open, it seems that there would either have to be a way to open different connections opened to create the models or that there would need to be a way to initiate the creation of the model for the sketches from the connection callback code in main.js.

I'm very new to MongoDB and Mongoose so I'm not sure if this is the correct way to think about creating models but given the needs of the feature, what would be the correct approach to opening the connection to the database and saving the sketches to the database once the save sketch function is called?

You may be overthinking this.

Just open your mongoose connection (a shared connection pool) via a mongoose.connect call during app start up and then create and save your Mongoose models whenever. Your models will use the shared connection pool as needed and will wait until the connection is established if necessary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM