存储与检索小型对象(Node.js):是否需使用数据库?
Hey there! Let's break this down based on your specific use case—totally normal to wonder about database choices when building your first production Node.js app, so let's keep it simple.
First, let's anchor back to your core requirements: max 20 inventory items, updated only once a week, needs to persist (so data doesn't vanish when your server restarts).
For your current needs, lighter storage is way more efficient
MongoDB is a great tool, but it's overkill for this scenario. Here are two simpler, better options:
- JSON file storage: This is perfect for tiny, infrequently updated datasets. You can just read/write your inventory array to a
inventory.jsonfile in your project. No extra services to set up, no learning curve for a database, and the code is straightforward.
Here's a quick example of how that might look:
Since you're only updating once a week, you don't have to worry about concurrent write conflicts—this will work flawlessly.const fs = require('fs').promises; const path = require('path'); // Fetch current inventory async function getInventory() { const fileContent = await fs.readFile(path.join(__dirname, 'inventory.json'), 'utf8'); return JSON.parse(fileContent); } // Save updated inventory async function saveInventory(inventory) { await fs.writeFile(path.join(__dirname, 'inventory.json'), JSON.stringify(inventory, null, 2)); } - SQLite: If you think you might add slightly more complex features down the line (like filtering items by category, or expanding beyond 20 entries), SQLite is a step up. It's a file-based relational database, so no separate server needed, but it supports SQL queries for more flexibility.
When would MongoDB make sense?
Hold off on MongoDB unless you have plans for:
- Scaling to hundreds/thousands of inventory items (and needing fast, complex queries)
- Deploying multiple server instances that need to share the same inventory data
- Using advanced features like aggregation pipelines or geospatial queries
- You're already familiar with MongoDB and prefer sticking with what you know
Final call
For your current setup, go with JSON file storage first. It's quick to implement, has zero overhead, and meets all your needs. If your app grows later, migrating to MongoDB (or any database) will be trivial because you only have 20 items to move.
内容的提问来源于stack exchange,提问作者c.gooderham94

