Nodejs,Mongoose,Express:类型:Schema.ObjectId,参考:'Account' 不起作用

Posted

技术标签:

【中文标题】Nodejs,Mongoose,Express:类型:Schema.ObjectId,参考:\'Account\' 不起作用【英文标题】:Nodejs, Mongoose, Express: type: Schema.ObjectId, ref: 'Account' not workingNodejs,Mongoose,Express:类型:Schema.ObjectId,参考:'Account' 不起作用 【发布时间】:2016-08-25 17:06:57 【问题描述】:

我刚刚开始使用 MEAN 堆栈,似乎无法让我的对象 ID 在多个架构之间共享。

简而言之:我希望将 Account 模型中的对象 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);

【问题讨论】:

您有具体的问题吗?您发布了所有代码,但完全不清楚您已经尝试将两个模型关联起来,以及失败的原因。 当代码运行时,它会添加到我的 db.profile 集合中,但“_creator”显示为一个空数组。因此,它从不从 Account 模型中注册 ObjectId,我不知道为什么。根据猫鼬文档,它应该是一个简单的引用,例如我在代码中的引用,但它只是返回一个空数组。我不确定我错过了什么。 您在哪里将帐户与代码中的配置文件相关联?使用所有添加的噪音很难遵循代码:-( 我刚刚找到它。谢谢你!我刚刚添加了代码。我的“_creator”字段是一个空白数组,因为我从未将该值分配给任何东西。 【参考方案1】:

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 与用户配置文件架构相关联。

如果任何阅读本文的人发现此答案有问题,请发表评论并告诉我。 IE。未来的安全问题、可扩展性、查询等。

感谢 robertklep 让我走上这条路。

【讨论】:

以上是关于Nodejs,Mongoose,Express:类型:Schema.ObjectId,参考:'Account' 不起作用的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Express 和 NodeJS 中针对 Mongoose 错误进行错误处理。

Nodejs+express+mongodb+mongoose

使用 Nodejs、Express、Mongoose 和 React 将图像上传到 MongoDB

如何在 mongodb 中自动插入记录(nodejs、express、mongoose)

如何在 NodeJS 的查询参数中传递时间戳(Express + Mongoose)

NodeJS/Express/Mongoose 出错 Can't set headers after they are sent