使用mongoose,node和express时,“model.find()不是函数”错误

时间:2017-05-20 23:21:02

标签: node.js express mongoose routes

我目前正在尝试使用node.js / express教程(来自Express in Action),但无法正确访问mongoose模型。我在名为“User”的var中调用该模块,我不断收到“User.find不是函数”的错误。

以下是models/user.js文件:

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;

以下是调用它的routes.js文件:

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;

最后这里是index.js文件,如果它是相关的

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.');
});

我尝试过所有类似问题的解决方案,但没有运气。

0 个答案:

没有答案