Saturday, 20 May 2017

"model.find() is not a function" error when using mongoose, node, and express

I'm currently trying to get a node.js/express tutorial working (from Express in Action), but haven't been able to access a mongoose model properly. I call the module in a var called "User" I keep getting the error that "User.find is not a function."

Here is the models/user.js file:

var
  bcrypt = require("bcrypt-nodejs"),
  mongoose = require("mongoose"),
  SALT_FACTOR = 10
;

var noop = function() {};

var userSchema = mongoose.Schema({
  displayName: String,
  bio: String
});

userSchema.pre("save", function(done) {
  var user = this;

  if (!user.isModified("password")) {
    return done();
  }

  bcrypt.genSalt(SALT_FACTOR, function(err, salt) {
    if (err) { return done(err); }
    bcrypt.hash(user.password, salt, noop, function(err, hashedPassword) {
      if (err) { return done(err); }
      user.password = hashedPassword;
      done();
    });
  });
});

userSchema.methods.checkPassword = function(guess, done) {
  bcrypt.compare(guess, this.password, function(err, isMatch) {
    done(err, isMatch);
  });
};

userSchema.methods.name = function() {
  return this.displayName || this.username;
};

var User = mongoose.model("User", userSchema);

module.exports = User;

Here is the routes.js file calling it:

var
  express  = require("express"),
  mongoose = require("mongoose"),
  flash    = require("connect-flash"),
  passport = require("passport"),
  router   = express.Router()
;

var User = ("./models/user");

router.use(function(req, res, next){
  res.locals.currentUser = req.user;
  res.locals.errors = req.flash("error");
  res.locals.infos = req.flash("info");
  next();
});

router.get("/", function(req, res, next) {
  User.find({}, function(err, users) {
    assert.equal(err, null);
    res.json(users);
  });
});

/* 
Original route, also doesn't work

router.get("/", function(req, res, next) {
  User.find()
    .sort({ createdAt: "descending" })
    .exec(function(err, users) {
      if (err) { return next(err); }
      res.render("index", { users: users });
  });
});
*/

module.exports = router;

Lastly here's the index.js file, in case it's relevant

var
  http         = require("http"),
  path         = require("path"),
  express      = require("express"),
  flash        = require("connect-flash"),
  session      = require("express-session"),
  cookieParser = require("cookie-parser"),
  logger       = require("morgan"),
  liquid       = require("shopify-liquid"),
  bodyParser   = require("body-parser"),
  mongoose     = require('mongoose')
;

var routes = require('./routes');
var app = express();

mongoose.connect('mongodb://localhost:27017/test');

app.set("port", process.env.PORT || 3000);

var engine = liquid({
    root: __dirname,  // for layouts and partials
    extname: '.liquid'
});
app.engine('liquid', engine.express()); 
app.set('views', ['./views', './views/partials', './views/layouts']); 
app.set('view engine', 'liquid');

var assetsPath = path.resolve(__dirname, "assets");
app.use("/assets", express.static(assetsPath));

app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({
  secret: "TKRv0IJs=HYqrvagQ#&!F!%V]Ww/4KiVs$s,<<MX",
  resave: true,
  saveUninitialized: true
}));
app.use(flash());
app.use(routes);

app.use(logger("dev"));

app.use(function(request, response) {
  response.status(404).render("404");
});

http.createServer(app).listen(3000, function(){
  console.log('App skeleton started on port 3000.');
});

I've tried the solutions suggested from all similar questions but had no luck.



via Max Antonucci

No comments:

Post a Comment