所以,我有一個不同的 mongodb 檔案相互關聯。我希望能夠訪問從父檔案一直到孫關系檔案的值的不同鍵及其值。這是我的設定。
const itemSchema = new mongoose.Schema({
name: String,
amount: mongoose.Decimal128
});
const Item = new mongoose.model("Item", itemSchema);
const sectionSchema = new mongoose.Schema({
name: String,
items: [itemSchema],
currentAmount: mongoose.Decimal128,
limitAmount: mongoose.Decimal128,
sectionStatus: Boolean
});
const Section = new mongoose.model("Section", sectionSchema);
const userSchema = new mongoose.Schema({
username: {
type: String,
required: true,
unique:true
},
email: {
type: String,
lowercase: true,
trim:true,
required: true,
unique: true
},
password: {
type: String,
required: true
},
sections: [sectionSchema]
const User = new mongoose.model("User", userSchema);
我還創建了虛擬檔案來填充資料庫,這樣我就可以將它們發送到 EJS 并設定網頁。
我試過了
User.find({}, function(err,foundUser){
let rUsername = foundUser.username;
let rSections = foundUser.sections;
// let rItems = rSections.items
// let rItems = foundUser.sections.items;
console.log(foundUser.sections);
console.log(foundUser.username);
});
我似乎無法記錄任何內容,因為它只是說undefined。我已經確保我的語法是正確的,因為它的格式與我所學的完全一致,并且在我的其他類似專案中它作業得很好。只是我以前從未做過“三重”嵌入。我還確保一切都正確連接:我的依賴項(express、body-parser、mongoose)、MongoDB 資料庫充滿了它們各自的集合并連接。我似乎無法在檔案或谷歌或 stackoverflow 上的任何地方找到答案。哈普請 x(
uj5u.com熱心網友回復:
您可以存盤對內部架構的參考及其populate:
const itemSchema = new mongoose.Schema({
name: String,
amount: mongoose.Decimal128,
});
const Item = new mongoose.model('Item', itemSchema);
const sectionSchema = new mongoose.Schema({
name: String,
items: [{
type: mongoose.Types.ObjectId,
ref: 'Item'
}],
currentAmount: mongoose.Decimal128,
limitAmount: mongoose.Decimal128,
sectionStatus: Boolean,
});
const Section = new mongoose.model('Section', sectionSchema);
const userSchema = new mongoose.Schema({
username: {
type: String,
required: true,
unique: true,
},
email: {
type: String,
lowercase: true,
trim: true,
required: true,
unique: true,
},
password: {
type: String,
required: true,
},
sections: [{
type: mongoose.Types.ObjectId,
ref: 'Section'
}],
});
const User = new mongoose.model('User', userSchema);
要檢索值:
.(async (req, res) => {
const user = await User.find({})
.populate({
path: 'sections',
populate: { path: 'items', }
}).exec();
if (!user) { // User not found }
let rUsername = user[0].username;
let rSections = user[0].sections;
console.log(foundUser.sections)
console.log(foundUser.username)
})
有關嵌套查詢人口的更多資訊,請參閱官方檔案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/483613.html
上一篇:如何從查詢中排除id陣列
