【问题标题】:mongoose subdocument field.id giving undefined猫鼬子文档 field.id 给出未定义
【发布时间】:2019-05-19 10:15:23
【问题描述】:

在此代码中,我需要使用其生成的 id 获取 batch_results,如中所述 猫鼬文档

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const config = require('../config/config');



// Result schema
const ResultsSchema = new Schema({
    subject_id: {
        type: mongoose.SchemaTypes.ObjectId,
        required: false
    },
    marks: {
        type: [String], // when needed to store absent as well
        required: false
    }
});

// Batch Schema
const BatchSchema = new Schema({
    student_base_no: {
        type: mongoose.SchemaTypes.ObjectId,
        required: false,
    },
    results: [ResultsSchema]
});

// Marks schema
const MarksSchema = new Schema({

    date: {
        type: Date,
        default: Date.now,
        required: true
    },
    year: {
        type: String,
        default: (new Date).getFullYear(),
        required: true
    },
    batch: {
        type: String,
        required: true
    },
    batch_results: [BatchSchema]

});



const Marks = module.exports = mongoose.model('marks', MarksSchema, 'marks');

使用此代码我尝试获取输出,

var a = Marks.batch_results.id(id)

但它一直说 Cannot read property 'id' of undefined

我尝试了很多,但效果不佳:( 请帮帮我...

【问题讨论】:

    标签: node.js mongodb mongoose mongoose-schema subdocument


    【解决方案1】:

    您需要更改批次和标记架构:

    const BatchSchema = new Schema({
        student_base_no: {
            type: mongoose.SchemaTypes.ObjectId,
            required: false,
        },
        results:{
             type: Schema.Types.ObjectId,
              ref: 'results' 
           }
    })
    

    【讨论】:

      猜你喜欢
      • 2015-01-06
      • 2023-03-06
      • 1970-01-01
      • 2015-06-26
      • 2015-10-01
      • 2017-05-07
      • 1970-01-01
      • 2012-11-07
      • 2017-12-05
      相关资源
      最近更新 更多