Nodejs,Mongoose,Express:类型:Schema.ObjectId,ref:' Account'不工作

时间:2016-04-30 15:48:02

标签: node.js express mongoose mean-stack mongoose-schema

我刚刚开始使用MEAN堆栈,似乎无法在多个模式中共享我的对象ID。

简而言之:我希望将来自帐户模型的对象ID存储为我的个人资料模型中的对象ID。

我正在使用localpassport身份验证。以下是我的App.js文件,路由和模型。

提前感谢您的帮助。

App.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({
    secret: 'keyboard cat',
    resave: false,
    saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
var Profile = require('./models/profile');
var Account = require('./models/account');
passport.use(new LocalStrategy(Account.authenticate()));
passport.serializeUser(Account.serializeUser());
passport.deserializeUser(Account.deserializeUser());

mongoose.connect('mongodb://127.0.0.1:27017/myapp');


// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});


module.exports = app;

Index.js

var express = require('express');
var passport = require('passport');
var Account = require('../models/account');
var Profile = require('../models/profile');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { user : req.user });
});

router.get('/register', function(req, res) {
    res.render('register', { });
});

router.post('/register', function(req, res) {
    Account.register(new Account({ username : req.body.username }), req.body.password, function(err, account) {
    if (err) {
        return res.render('register', { account : account });
    }

    passport.authenticate('local')(req, res, function () {
        res.redirect('/');
    });        
   });
});

router.get('/login', function(req, res) {
    res.render('login', { user : req.user });
});

router.post('/login', passport.authenticate('local'), function(req, res) {
    res.redirect('/profile');
});

router.get('/logout', function(req, res) {
    req.logout();
    res.redirect('/');
});

router.get('/profile', function(req, res, next) {
    res.render('profile', { user : req.user});
});

router.post('/profile', function(req, res) {
    var basicProfile = new Profile();

    basicProfile.firstname = req.body.firstname,
    basicProfile.middlename = req.body.middlename,
    basicProfile.lastname = req.body.lastname,
    basicProfile.contactinfo.phonenumber = req.body.phonenumber,
    basicProfile.contactinfo.address.street = req.body.street,
    basicProfile.contactinfo.address.city = req.body.city,
    basicProfile.contactinfo.address.state = req.body.state,
    basicProfile.contactinfo.address.zip = req.body.zip

    basicProfile.save(function(err, profile){
        if(err){
        return res.render('profile', { profile : profile });
        }
        return res.redirect('/');
    });
});

router.get('/ping', function(req, res) {
    res.status(200).send("pong!");
});

router.get('/profile', function(req, res) {
    res.render('profile')
})

module.exports = router;

帐户模型

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var passportLocalMongoose = require('passport-local-mongoose');

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

Account.plugin(passportLocalMongoose);

module.exports = mongoose.model('Account', Account);

个人资料模型

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var ProfileSchema = new Schema({
    _creator: [{type: mongoose.Schema.Types.ObjectId, ref: 'Account'}],

    firstname: String,
    middlename: String,
    lastname: String,
    contactinfo: {
        phonenumber: String,
        address: {
            street: String,
            city: String,
            state: String,
            zip: String
        }
    }

});


module.exports = mongoose.model('Profile', ProfileSchema);

1 个答案:

答案 0 :(得分:0)

<强> Profile.js

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var ProfileSchema = new Schema({
    _creator: [{type: mongoose.Schema.Types.ObjectId, ref: 'Account'}],

    firstname: String,
    middlename: String,
    lastname: String,
    contactinfo: {
        phonenumber: String,
        address: {
            street: String,
            city: String,
            state: String,
            zip: String
        }
    }

});


module.exports = mongoose.model('Profile', ProfileSchema);

<强> Index.js

var express = require('express');
var passport = require('passport');
var Account = require('../models/account');
var Profile = require('../models/profile');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { user : req.user });
});

router.get('/register', function(req, res) {
    res.render('register', { });
});

router.post('/register', function(req, res) {
    Account.register(new Account({ username : req.body.username }), req.body.password, function(err, account) {
    if (err) {
        return res.render('register', { account : account });
    }

    passport.authenticate('local')(req, res, function () {
        res.redirect('/');
    });        
   });
});

router.get('/login', function(req, res) {
    res.render('login', { user : req.user });
});

router.post('/login', passport.authenticate('local'), function(req, res) {
    res.redirect('/profile');
});

router.get('/logout', function(req, res) {
    req.logout();
    res.redirect('/');
});

router.get('/profile', function(req, res, next) {
    res.render('profile', { user : req.user});
});

router.post('/profile', function(req, res) {
    var basicProfile = new Profile();

    basicProfile._creator = req.user._id
    basicProfile.firstname = req.body.firstname,
    basicProfile.middlename = req.body.middlename,
    basicProfile.lastname = req.body.lastname,
    basicProfile.contactinfo.phonenumber = req.body.phonenumber,
    basicProfile.contactinfo.address.street = req.body.street,
    basicProfile.contactinfo.address.city = req.body.city,
    basicProfile.contactinfo.address.state = req.body.state,
    basicProfile.contactinfo.address.zip = req.body.zip

    basicProfile.save(function(err, profile){
        if(err){
        return res.render('profile', { profile : profile });
        }
        return res.redirect('/');
    });
});

router.get('/ping', function(req, res) {
    res.status(200).send("pong!");
});

router.get('/profile', function(req, res) {
    res.render('profile')
})

module.exports = router;

将_creator添加到定位来自数据库的用户ID的路​​由,该数据库现在将该对象ID与用户配置文件架构相关联。

如果有人在阅读此内容时发现此答案存在问题,请发表评论并告知我们。 I.E.安全问题,可扩展性,查询等等。

感谢robertklep让我走上这条道路。