猫鼬findOne不是函数

时间:2018-12-08 10:42:56

标签: node.js mongodb express mongoose

我刚刚尝试使用mongodb 3.2.21版创建简单的登录和注册表单,因为我拥有32位CPU的Windows 7,因此代码如下

var express = require('express');
var app = express();
var mongoose = require('mongoose'); 
var consolidate = require('consolidate');
var http = require('http').Server(app);
var io = require('socket.io')(http);
var multer = require('multer')
var upp = multer()
var bodyParser = require('body-parser')
var router = express.Router()


app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(upp.array()); 

app.use(express.static('public'));
app.engine('html', consolidate.mustache);
app.set('view engine', 'html');
app.set('views', __dirname + '/views');
var mongoDB = 'mongodb://localhost/my_database';
mongoose.connect(mongoDB, {useNewUrlParser: true});
// Get Mongoose to use the global promise library
mongoose.Promise = global.Promise;
//Get the default connection
var db = mongoose.connection;
if(db){
console.log('connection')
  }
 //Bind connection to error event (to get notification of connection errors)
 db.on('error', console.error.bind(console, 'MongoDB connection error:'));



var Schema = mongoose.Schema;

var SomeModelSchema = new Schema({
username: String,
password: String
});

var SomeModel = mongoose.model('SomeModel', SomeModelSchema );

var newuser = new SomeModel();



app.get('/', function(req, res){
res.render('mainpage')
})
app.get('/reg', function(req, res){
     res.render('reg')
}) 

app.post('/reeg', function(req,res){
newuser.username = req.body.username;
newuser.password = req.body.password;

newuser.save(function (err, savedObject){
if (err){ 
  console.log(err)
}else{
console.log(savedObject);
res.sendFile(__dirname + '\\views\\mainpage.html')
}})

}); 

app.post('/login', function(req,res){
 var userr = req.body.usernamee
 var pass = req.body.passwordd
 newuser.findOne({username: userr, password: pass}).exec(), 
 function(err,obj){
           if(err) {return res.status(404)
           }else if(!obj){
             res.send('notregistered')
           }if(obj){
             res.send('hey' + userr)
           }



          }})             


         http.listen('8080')

这给了我这个错误image of error

那么这是什么问题?我尚未使用快递路由器,此代码位于一个文件中

1 个答案:

答案 0 :(得分:3)

newuser不是模型,它是SomeModel-list of methods here

的实例

findOne是模型的方法-SomeModel list of methods here

因此替换:newuser.findOneSomeModel.findOne

为了更好的可读性,异步/等待功能,对象解构示例等最佳实践,我重写了总体代码:

'use strict';

const path = require('path');
const http = require('http');
const express = require('express');
const socketIO = require('socket.io');
const bodyParser = require('body-parser');
const consolidate = require('consolidate');


// DB connection
const mongoose = require('mongoose');
const connectionString = 'mongodb://localhost/my_database';
mongoose.Promise = global.Promise;

mongoose
  .connect(connectionString, {useNewUrlParser: true})
  .then(() => {
    console.log('Connection to database established');
  })
  .catch(error => {
    console.error('MongoDB connection error:', error.message);
    process.exit(-1);
  });
// End of: DB connection


// Defining DB schemas and models
const Schema = mongoose.Schema;
const UserSchema = new Schema({
  username: String,
  password: String
});
const User = mongoose.model('User', UserSchema);
// End of: Defining DB schemas and models


// Initial app configuration
const app = express();
const server = http.Server(app);
const io = socketIO(server);

app.engine('html', consolidate.mustache);
app.set('view engine', 'html');
app.set('views', path.join(__dirname, 'views'));

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static('public'));
// End of: Initial app configuration


// App route handlers
app.get(
  '/',
  (req, res) => {
    res.render('mainpage');
  });

app.get(
  '/reg',
  (req, res) => {
    res.render('reg');
  });

app.post(
  '/reg',
  async (req, res) => {
    try {
      const {username, password} = req.body;
      const user = await User.create({username, password});
      console.log('Created user:', user);
      res.sendFile(path.join(__dirname, 'views', 'mainpage.html'));
    }
    catch (error) {
      res.status(500).send(error.message);
    }
  });

app.post(
  '/login',
  async (req, res) => {
    try {
      const {username, password} = req.body;
      const user = await User.findOne({username, password}).select('-password').lean();
      if(!user) {
        res.send('User: ' + username +' not registered');
        return;
      }

      res.send('hey ' + username);
    }
    catch (error) {
      res.status(500).send(error.message);
    }
  });
// End of: App route handlers


// Binding http listener to port
server.listen('8080');

注意:lean是查询方法manual here

修复您的登录表格:

<form action="/login" method="POST"> 
  <input type="text" placeholder="username" name="username"> 
  <input type="password" placeholder="pass" name="password"> 
  <button type="submit">Login</button> <br/>
  or <strong><a href="/reg">Sign Up</a></strong>
</form>

P.S。如果出现问题,请写评论。