Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/42.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 护照和猫鼬问题_Node.js_Mongoose_Passport.js - Fatal编程技术网

Node.js 护照和猫鼬问题

Node.js 护照和猫鼬问题,node.js,mongoose,passport.js,Node.js,Mongoose,Passport.js,嗨,我有这个型号: user.js // app/models/user.js // load the things we need var Schema = require('mongoose').Schema; var bcrypt = require('bcrypt-nodejs'); var db = require('mongoose'); // define the schema for our user model // create the model for u

嗨,我有这个型号:

user.js

    // app/models/user.js
// load the things we need
var Schema = require('mongoose').Schema;
var bcrypt   = require('bcrypt-nodejs');
var db = require('mongoose');

// define the schema for our user model

// create the model for users and expose it to our app

    module.exports = function(app){

        var userSchema = Schema({

        local            : {
            email        : String,
            password     : String,
        },
        facebook         : {
            id           : String,
            token        : String,
            email        : String,
            name         : String
        },
        twitter          : {
            id           : String,
            token        : String,
            displayName  : String,
            username     : String
        },
        google           : {
            id           : String,
            token        : String,
            email        : String,
            name         : String
        }

    });

    // methods ======================
    // generating a hash
    userSchema.methods.generateHash = function(password) {
        return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
    };

    // checking if password is valid
    userSchema.methods.validPassword = function(password) {
        return bcrypt.compareSync(password, this.local.password);
    };


    return db.model('User', userSchema);

};
post.js

    var db = require('mongoose');


module.exports = function(app){
    var Schema = require('mongoose').Schema;

    var post = Schema({
        title: String,
        private: Boolean,
        text: String,
        tags: [],
        createdAt:  { type: Date, default: Date.now }
    });

    return db.model('post', post);

};
和passport配置文件:

    // config/passport.js

// load all the things we need
var db = require('../config/db_connect')();

var LocalStrategy   = require('passport-local').Strategy;

// load up the user model

var User = db.model('User');
// expose this function to our app using module.exports
module.exports = function(passport) {

    // =========================================================================
    // passport session setup ==================================================
    // =========================================================================
    // required for persistent login sessions
    // passport needs ability to serialize and unserialize users out of session

    // used to serialize the user for the session
    passport.serializeUser(function(user, done) {
        done(null, user.id);
    });

    // used to deserialize the user
    passport.deserializeUser(function(id, done) {
        User.findById(id, function(err, user) {
            done(err, user);
        });
    });

    // =========================================================================
    // LOCAL SIGNUP ============================================================
    // =========================================================================
    // we are using named strategies since we have one for login and one for signup
    // by default, if there was no name, it would just be called 'local'

    passport.use('local-signup', new LocalStrategy({
        // by default, local strategy uses username and password, we will override with email
        usernameField : 'email',
        passwordField : 'password',
        passReqToCallback : true // allows us to pass back the entire request to the callback
    },
    function(req, email, password, done) {

        // asynchronous
        // User.findOne wont fire unless data is sent back
        process.nextTick(function() {

        // find a user whose email is the same as the forms email
        // we are checking to see if the user trying to login already exists
        User.findOne({ 'local.email' :  email }, function(err, user) {
            // if there are any errors, return the error
            if (err)
                return done(err);

            // check to see if theres already a user with that email
            if (user) {
                return done(null, false, req.flash('signupMessage', 'That email is already taken.'));
            } else {

                // if there is no user with that email
                // create the user
                var newUser            = new User();

                // set the user's local credentials
                newUser.local.email    = email;
                newUser.local.password = newUser.generateHash(password);

                // save the user
                newUser.save(function(err) {
                    if (err)
                        throw err;
                    return done(null, newUser);
                });
            }

        });    

        });

    }));

};
至少是我的app.js

var express = require('express')
, load = require('express-load')
, bodyParser = require('body-parser')
, cookieParser = require('cookie-parser')
, passport = require('passport')
, flash    = require('connect-flash')
, mongoose = require('mongoose')
, session = require('express-session')
, app = express();



require('./config/passport')(passport);

app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(cookieParser('blog'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
// required for passport
app.use(session({
  secret: 'appsecret',
  resave: false,
  saveUninitialized: true,
  cookie: {
    secure: true,
    maxAge: new Date(Date.now() + 3600000)
  }
}));
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session
app.use(express.static(__dirname + '/public'));

load('models')
    .then('controllers')
    .then('routes')
    .into(app);

require('./routes/login.js')(app, passport); 


app.listen(3030, function(){
  console.log("Blog no ar.");
});
但当我尝试运行我的应用程序时,我遇到了一个异常:

    /home/caio/workspace/personal-blog/node_modules/mongoose/lib/index.js:323
      throw new mongoose.Error.MissingSchemaError(name);
            ^
MissingSchemaError: Schema hasn't been registered for model "User".
Use mongoose.model(name, schema)
    at Mongoose.model (/home/caio/workspace/personal-blog/node_modules/mongoose/lib/index.js:323:13)
    at Object.<anonymous> (/home/caio/workspace/personal-blog/config/passport.js:10:15)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object.<anonymous> (/home/caio/workspace/personal-blog/app.js:13:1)
/home/caio/workspace/personal blog/node\u modules/mongoose/lib/index.js:323
抛出新mongoose.Error.MissingSchemaError(名称);
^
MissingSchemaError:尚未为模型“用户”注册架构。
使用mongoose.model(名称、模式)
在Mongoose.model(/home/caio/workspace/personal blog/node_modules/Mongoose/lib/index.js:323:13)
反对。(/home/caio/workspace/personal blog/config/passport.js:10:15)
在模块处编译(Module.js:456:26)
在Object.Module.\u extensions..js(Module.js:474:10)
在Module.load(Module.js:356:32)
在Function.Module.\u加载(Module.js:312:12)
at Module.require(Module.js:364:17)
根据需要(模块js:380:17)
反对。(/home/caio/workspace/personal blog/app.js:13:1)

我正在注册我的用户模型,但mongoose无法识别,任何人都可以帮助我?

在你的app.js中,在express之前先加载mongoose

var mongoose = require('./config/mongoose'),
express = require('./config/express');

var db = mongoose();
var app = express();
别忘了注册模型。你的代码应该是

return db.model('User', userSchema);

好的,mongoose模型需要一个模式

而不是:

var User = db.model('User');
做一些类似于:

var Schema = require('mongoose').Schema
var userSchema = new Schema({
  name: {
    type: String,
 default: 'hahaha'
  }
});
var User = db.model('User', userSchema);
您在哪里调用require('user')或require('post')?