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

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

    });

我似乎无法记录任何内容,因为它只是说 未定义。 我已经确保我的语法是正确的,因为这完全按照我所教的格式进行,并且在我的其他类似项目中它工作得很好。只是我以前从未做过 'tripple' 嵌入。 我还确保一切都正确连接:我的依赖项(express、body-parser、mongoose)、MongoDB 数据库已填充了它们各自的集合并已连接。我似乎无法在文档中或 google 或 Whosebug 上的任何地方找到答案。 halp plz 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)
})

关于嵌套查询人口的更多信息见官方docs