データベースとセッションストアにすべてのデータを保存する e コマース Web サイトを作成しています。ログインしたユーザーの場合、ログイン資格情報のみがセッション ストアに保存されます。そのため、Web サイトを初めて実行するときはいつでも、セッション ストアから取得したデータからデータベースからデータをフェッチする必要がありますが、この目的でミドルウェアを使用すると、リクエストごとにミドルウェアが実行されるため効率的ではありません。それで、この問題を解決する方法はありますか、またはこの問題に対するより効率的なより良い解決策はありますか? また、なぜセッション ストアにデータを直接保存しないのか不思議に思うかもしれません。したがって、問題は、セッションストアからデータを取得すると、マングースモデルの形式で返されないため、データベースを1回呼び出す必要があることです。私はmongo store、express、node、ejsを使用しています。
これは、ログイン時にセッション ストアに保存されている ID を使用して、マングース モデルのデータベースからデータを取得するためにインデックス ファイルで使用するミドルウェアです。
app.use(async (req, res, next) => {
try {
if(req.session.userid) {
req.user = await user.findById(userid)
}
} catch(err) {
res.redirect('/' + req.oldUrl + '?err=UserNotFound')
}
next()
})
app.use(session({
secret: 'secret',
saveUninitialized: false,
resave: false,
cookie: {
maxAge: 1000 * 60 * 60 * 24 * 365 * 100,
secure: false
},
store: store
}))
これは私のマングース モデルです
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const userschema = new Schema({
Name : {
type : String,
required : true
},
Email : {
type : String,
required : true
},
Password : {
type : String,
required : true
},
IsSeller : {
type : Boolean,
defualt : false
},
Shopname : {
Type : String,
default : "-"
},
Cart : {
Items : [
{
productId : {
type : Schema.Types.ObjectId,
ref : 'product',
required : true
},
quantity : {
type : Number,
required : true
}
}
]
},
Myproducts : {
items : [
{
productId : {
type : Schema.Types.ObjectId,
ref : 'product',
required : true
},
quantity : {
type : Number,
required : true
}
}
]
},
Sdate : {
type : String,
default : "-"
}
})
module.exports = mongoose.model('user', userschema)