简体   繁体   中英

unable to query a model on mongoose

So I'm messing around with mongoose express trying to implement the MVC pattern. I'm trying to basically print out my documents in the kittens collection but absolutely have no idea how to. I've followed countless tutorials and something keeps on going wrong. Most of the tutorials I look at just shows them putting the code in one single file which is not ideal. My routes do work as I've tested them with my views (I haven't included them). The error I am getting when I am accessing /indexoflistcontrollersget is a referenceError on kitty (line 10 in listControllers.js). Apparently kitty is not defined but I'm sure it should be since that file requires homemodel.js hence it should already have ran that code?

These are my files:

app.js

var express = require('express');
var http = require('http');
var path = require('path');
var handlebars  = require('express-handlebars'), hbs;
var app = express();
var db = require('./db')

require('./router')(app);

app.set('port', 1337);
app.set('views', path.join(__dirname, 'views'));

/* express-handlebars - https://github.com/ericf/express-handlebars
A Handlebars view engine for Express. */
hbs = handlebars.create({
   defaultLayout: 'main'
});

app.engine('handlebars', hbs.engine);
app.set('view engine', 'handlebars');

app.use(express.static(path.join(__dirname, 'static')));

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

// Connect to Mongo on start
db.connectDB();

db.js

var mongoose = require('mongoose');
exports.connectDB = function() {
mongoose.connect('mongodb://localhost:27017/test');
console.log("CONNECTED TO MONDO")
}

model/homemodel.js

var mongoose = require('mongoose');

var Schema = mongoose.Schema;

var kittySchema = new Schema({
    name: String
});

mongoose.model('kitty', kittySchema);

controller/listControllers.js

var express = require('express');
var router = express.Router();
var modelList = require('../model/homemodel.js');
var mongoose = require('mongoose');
exports.IndexOfListControllerGET = function(request, response){
//This is another controllers
//GET METHOD

  mongoose.model('kitty').find(function(err,kitty){
response.send(kitty);

  });


}

Please help, been stuck at this very simple problem for a long time now.

EDIT = So I fixed the error. was passing the wrong parameters. But only [] is printing out. When I access the kittens collections using the mongo terminal, I can see the entries I've already put in. How can I display those entries on the page?

first i guess in "homemodel.js" you need a module.exports :

    module.exports = mongoose.model('kitty', kittySchema);

try this in "controller/listControllers.js":

var express = require('express');
var router    = express.Router();
var modelList = require('../model/homemodel.js');    

var IndexOfListControllerGET = function (request, response) {

var query = { name: 'pichou' };

modelList.find(query, function (err, kitty) {
    if (err) throw err;

    return response.send(kitty);
});
}

module.exports = IndexOfListControllerGET;

EDIT : 'Model.find' need a condition, for example you search the name of the kitty 'pichou', you can send the object '{ name: 'pichou' }', or list all results by sending empty object '{}'

To send back all of the records about "kitty"s, try this code:

modelList.find({}, function (err, kittyRecords){
  if (err) throw new Error("Error in finding kittys : " + err);
  console.log("Kittys: ", kittyRecords);
  return response.send(kittyRecords);
});

The empty object passed to the mongoose model will match all the records it encounters. The console.log will let you see if the records match what is going to the webpage. It looks like the code from lefdilia has the answer, however will only return for the name of 'pichou'. As suggested above, you should export the model to have an explicit handle on it.

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