簡體   English   中英

如何從 mongodb 中的嵌套數組中獲取值

[英]How to fetch values from nested array in mongodb

我正在使用 mongodb 數據庫來存儲數據並使用 mongoose 來制作架構。以下是我的架構:

費用.js

const mongoose = require('mongoose');

const ExpenseSchema = new mongoose.Schema({

  payerid:{
      type: String,
      required: true
  },
  paid:{
    type: Number,
    require: true
  },
  owers:[
      {
     owerid:{
       type:String
     },
     amt:{
       type: Number
     }  
    }
  ],
  name:{
    type: String,
    required: true
  },
  amount:{
      type: Number,
      require: true
  }
});

const expense = mongoose.model('expense',ExpenseSchema);
module.exports = expense;

這是我的數據庫結構:

在此處輸入圖像描述

我想從數組中獲取oweridamt值。如何獲取這個我不明白。有人告訴我。

你可以這樣做:

const Expenses= require('../models/expense');

const getExpense = async (expenseId) => {
  try {
    const expense = await Expenses.findById(expenseId);  
    // Now, you can access owers array of the document
    console.log(expense.owers);
    return expense.owers;
  } catch (error) {
    console.log('ERROR: ', error);
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM