[英]How do I access embedded Mongodb document through Jade and NodeJS?
[英]In nodejs, how do I traverse between embedded mongodb documents to get the values of their keys
所以,我有一個不同的 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(
您可以存儲對內部模式的引用並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)
})
有關嵌套查詢人口的更多信息,請參閱官方文檔。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.