私は現在、ユーザーが PassportJs と Mongoose でログインできるようにする小さな単一ページのアプリに取り組んでいます。
私がやろうとしていることの 1 つは、ユーザーがログインできるようにすることです。各ユーザーには、そのユーザーに関連付けられたアイテムである一意の todo/タスク リストがあります。
私は最初の部分を行うことができました...ユーザーはログインでき、エクスプレス/パスポートセッションはjade #{user.username}を使用してアクセスできるため、ログインすると、ユーザーに「ようこそ、[user.username]」が表示されます。
ここで、フォーム (ユーザーがログインしたときにアクセス可能) を追加すると、フォームは未定義と表示されます。問題を引き起こしているのが私のMongooseスキーマ設計なのかルートなのかはわかりません。これを読んでくれてありがとう。ここに私のコードがあります:
マングーススキーマ
mongoose.connect('mongodb://localhost/poplivecore')
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;
var user = new Schema({
username: String,
password: String,
email: String,
todos: [Todo]
});
var Todo = new Schema({
name: {type: String, default : ''},
user: {type: Schema.ObjectId, ref: 'user'},
createdAt : {type : Date, default : Date.now}
})
var Todo = mongoose.model('Todo', Todo);
var user = mongoose.model('user', user);
ここに私の Express ルートがあります: //WORKING....このルートは、ログインしているユーザーに表示されるもので、フォーム投稿で
app.get('/home', ensureAuthenticated ,function(req, res){
res.render('home', { user: req.user});
});
//WORKING...このルートにより、ユーザーはログインを投稿/送信できます
app.post('/login',
passport.authenticate('local', { failureRedirect: '/login', failureFlash: true }),
function(req, res) {
res.redirect('/home');
});
//WORKING....This route allows user to create a user/account
app.post('/create', function(req, res, next){
var user = new user({
"username": req.body.username,
"password" : req.body.password,
"email" : req.body.email});
user.save(function (err) {
if (!err) {
res.redirect('/home');
}
else {
res.redirect('/');
}
});
});
**//NOT WORKING..Post used in the form inside the logged in Area, that adds a 'todo'**
app.post('/todo', function(req, res){
var todo = new todo(req.body.name);
todo.save(function (err) {
if (!err) {
res.redirect('/home');
}
else {
res.redirect('/fail');
}
});
});
Todo を追加するための Jade Form
enter code here
form(method='post', action='/todo')
//input(type='hidden', value= user._id)#userId
fieldset
label Todo
div.input
input(name='todo.name', type='todo.name', class='xlarge')
div.actions
input(type='submit', value='Save', class='btn primary')
button(type='reset', class='btn') Cancel
もっとコードを見る必要がある場合は、github に投稿できます...ありがとう。
「numbers1311407」の提案に従って更新 * todo の新しいポスト ルート、スキーマとルートの両方で todo を「Todo」に変更*
app.post('/todo', function(req, res){
var todo = new Todo({name : req.body["Todo.name"]});
todo.save(function (err) {
if (!err) {
res.redirect('/home');
}
else {
res.redirect('/fail');
}
});
});