我遵循 mongoose 檔案來填充相關物件,每次 authSessions 為空。我可以在 mongo 會話中看到與相關的 userId 欄位一起填充。我也嘗試在填充函式中指定“路徑”和“模型”選項,但這也不起作用。有人有想法么?
//Session.js
const SessionSchema = new mongoose.Schema({
_id: Schema.Types.ObjectId,
sessionId: { type: String, index: true },
createdDate: { type: Date, default: Date.now },
revoked: Boolean,
revokedAt: Date,
userId: {type: Schema.Types.ObjectId, ref: 'User', index: true}
})
module.exports = mongoose.models.Session || mongoose.model('Session', SessionSchema);
//User.js
const UserSchema = new mongoose.Schema({
_id: Schema.Types.ObjectId,
username: { type: String, index: true },
email: { type: String, index: true },
password: String,
registrationDate: { type: Date, default: Date.now },
authSessions: [{type: Schema.Types.ObjectId, ref: 'Session'}]
})
module.exports = mongoose.models.User || mongoose.model('User', UserSchema);
const user = await User.findById(session.userId).populate('authSessions').exec();
console.log(user) //authSessions is empty
{
_id: new ObjectId("62b6ea393e042868caa68c7d"),
username: 'asdfasdfasdf',
email: '[email protected]',
password: '[email protected]',
authSessions: [], //empty here always
registrationDate: 2022-06-25T10:58:01.709Z,
__v: 0
} ```
uj5u.com熱心網友回復:
MongoDB,以及擴展mongoose,不會自動為您創建關系。
如果您創建Session檔案,則需要將其顯式添加到User檔案populate中才能作業:
// create a new session document and save it
const userSession = new Session(…);
await userSession.save();
// !! update the user document and save it
user.authSessions.push(userSession);
await user.save();
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/495735.html
上一篇:Mongodb嵌套物件id
