简体   繁体   中英

Mongoose model is not returning data

I'm trying to setup a model but there is no data rendering on the page (using a handlebars view engine).

I have the following in an app.js file:

// Mongoose setup
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/nickinumbers');

And then this is the model I setup for the data I need returned this is ina nickinumbers.js file:

 var mongoose = require('mongoose');
 var Schema = mongoose.Schema;
 var NickiNumberSchema = new Schema({
   number: {type: 'String', required: true},
   firstName: {type: 'String'}
 });
 var NickiNumber = mongoose.model('Nickinumber', NickiNumberSchema);
 module.exports = NickiNumber;

Finally, my index.js router file contains:

var express = require('express');
var router = express.Router();

var NickiNumber = require('../models/nickinumbers');
    router.get('/', function(req, res) {
        NickiNumber.find(function(err, nums) {
            if (err) return console.error(err);
            res.render('index', {title: 'Users', nums: nums});
    }); 
});



module.exports = router;

I'm not seeing any errors on the server or in the console and I can't figure out why this isn't working. Any help is appreciated!

In find function first parameters is query condition then apply callback .

so you should use query condition {} to get all records or can apply your query. so should use NickiNumber.find({}, function(...

Query should be like:

var express = require('express');
var router = express.Router();

var NickiNumber = require('../models/nickinumbers');
router.get('/', function(req, res) {
        NickiNumber.find({}, function(err, nums) {
            if (err) return console.error(err);
            res.render('index', {title: 'Users', nums: nums});
    }); 
});

module.exports = router;

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