SailsJs v1.0.0-49启动调用sails.getDatastore报TypeError问题求助
Hey there, let's work through this issue together! The error you're hitting is almost certainly tied to the early pre-release version of Sails.js you're using (v1.0.0-49) — back then, the API hadn't fully stabilized yet. Here are actionable fixes to get your MongoDB manager access working without relying on Waterline models:
1. Use Direct Datastore Access Instead of getDatastore()
In early v1.0 pre-releases, the sails.getDatastore() method either didn't exist or wasn't fully implemented. Instead, you can directly access the datastore instance from the built-in sails.datastores object.
Example Code:
// Access your default datastore (replace with your custom name if needed) const datastore = sails.datastores.default; // Grab the native MongoDB manager const db = datastore.manager; // Now run native MongoDB operations, e.g.: const targetCollection = db.collection('your_collection_name'); const results = await targetCollection.find({}).toArray();
2. Make Sure Code Runs After Sails is Fully Ready
Even with direct access, you need to ensure Sails has finished initializing its datastores before trying to access the manager. Here's how to handle this in different contexts:
In config/bootstrap.js:
module.exports.bootstrap = async function(done) { // Wait for Sails to finish launching before accessing datastores sails.on('ready', async () => { const datastore = sails.datastores.default; if (!datastore?.manager) { return done(new Error('MongoDB datastore failed to initialize')); } const db = datastore.manager; // Run your startup MongoDB operations here console.log('Successfully connected to MongoDB via native manager'); }); done(); };
In a Service:
Don't try to access the datastore during service initialization. Wrap your logic in an async method that runs when needed:
// api/services/MongoService.js module.exports = { async fetchRecentData() { // Double-check the datastore is ready if (!sails.datastores.default?.manager) { throw new Error('MongoDB datastore isn\'t ready yet'); } const db = sails.datastores.default.manager; const collection = db.collection('your_collection'); return await collection.find({}).limit(10).sort({ createdAt: -1 }).toArray(); } };
3. Upgrade to a Stable Sails.js Version
The best long-term fix is to move away from the pre-release v1.0.0-49 to a stable v1.x release. Later versions formalized the sails.getDatastore() method, so your original code would work as expected:
// Works reliably in stable Sails.js v1.x+ const db = sails.getDatastore().manager;
Stable versions also come with bug fixes, security patches, and better documentation that will save you headaches down the line.
内容的提问来源于stack exchange,提问作者galgo

