简体   繁体   English

在nodejs中,如何在嵌入的mongodb文档之间遍历以获取其键的值

[英]In nodejs, how do I traverse between embedded mongodb documents to get the values of their keys

So, I have a different mongodb documents in relationship with one another.所以,我有一个不同的 mongodb 文档相互关联。 I want to be able to get access to the the different keys and their values starting with the parent document all the way down to the values of the grandchild relational document.我希望能够访问从父文档一直到孙关系文档的值的不同键及其值。 This is the setup I have.这是我的设置。

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);

I've also created dummy documents to fill the database so I can then send them to EJS and set up the webpage.我还创建了虚拟文档来填充数据库,这样我就可以将它们发送到 EJS 并设置网页。

I've tried我试过了

    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);

    });

I cant seem to get anything to log as it just says undefined .我似乎无法记录任何内容,因为它只是说undefined I've made sure my syntax is correct as this exactly formatted as I was taught to and in my other similiar projects it works just fine.我已经确保我的语法是正确的,因为它的格式与我所学的完全一致,并且在我的其他类似项目中它工作得很好。 It's just I've never made a 'tripple' embed before.只是我以前从未做过“三重”嵌入。 I've also made sure everything is hooked up correctly: my dependencies (express, body-parser, mongoose), the MongoDB database is filled with their respective collections and connected.我还确保一切都正确连接:我的依赖项(express、body-parser、mongoose)、MongoDB 数据库充满了它们各自的集合并连接。 I cant seem to find the answer in the documentation or anywhere on google or stackoverflow.我似乎无法在文档或谷歌或 stackoverflow 上的任何地方找到答案。 halp plz x(哈普请 x(

You could store the reference to the inner schemas and populate them:您可以存储对内部模式的引用并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);

To retrieve the values:要检索值:

.(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)
})

For more information on nested query population see the official docs .有关嵌套查询人口的更多信息,请参阅官方文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM