0

I have ArticlesController.js

const Articles = require('../models/Articles');

module.exports = {
  list: async(req, res) => {
    const articles = await Articles.find({});
    console.log(articles);
    res.status(200).json({
      message: 'Articles'
    });
  }
};

models/Articles.js

module.exports = {

  attributes: {
    title: {
      type: 'String'
    },
    body: {
      type: 'String'
    }
  },
  datastore: 'mongodb'
};

config/datastores.js

module.exports.datastores = {
  mongodb: {
    adapter: 'sails-mongo',
    url: 'mongodb://localhost:27017/sails-crud'
  },
};

package.json

"dependencies": {
    "@sailshq/connect-redis": "^3.2.1",
    "@sailshq/lodash": "^3.10.3",
    "@sailshq/socket.io-redis": "^5.2.0",
    "grunt": "1.0.4",
    "mongodb": "^2.2.25",
    "sails": "^1.4.2",
    "sails-hook-grunt": "^4.0.0",
    "sails-hook-orm": "^3.0.2",
    "sails-hook-sockets": "^2.0.0",
    "sails-mongo": "^1.2.0"
  }

But this is the error I get

error: Sending 500 ("Server Error") response: TypeError: Articles.find is not a function

I have tried using find.exec as well, same error with that as well. Help me resolve it.

Vinita
  • 1,834
  • 2
  • 8
  • 20
  • have you created the collection? – MWO Apr 04 '21 at 12:21
  • no, not manually, do I have to create it from the Command line separately, can't I do something like creating it using the api and write the Articles.create() in controllers? – Vinita Apr 04 '21 at 12:29
  • 1
    You can use the api but before you call 'find' the collection has to exist. something like that: MongoClient.connect(url, function(err, db) { if (err) throw err; var dbo = db.db("mydb"); dbo.createCollection("Articles", function(err, res) { if (err) throw err; console.log("Collection created!"); db.close(); }); }); – MWO Apr 04 '21 at 12:48
  • ok understood, thanks – Vinita Apr 04 '21 at 12:49
  • I created the collection using a blueprint and it added data to my local mogodb compass, but still this find throws the same error – Vinita Apr 04 '21 at 12:55
  • 1
    this is probably because your Articles import is basically just an object. you have to connect to your db again and call find like so: MongoClient.connect(url, function(err, db) { if (err) throw err; var dbo = db.db("sails-crud"); dbo.collection("Articles").find({}).toArray(function(err, result) { if (err) throw err; console.log(result); db.close(); }); }); – MWO Apr 04 '21 at 12:59
  • but this is the traditional mongo way. I might be missing the sails part – MWO Apr 04 '21 at 13:24

0 Answers0