猫鼬子文档 field.id 给出未定义
Posted
技术标签:
【中文标题】猫鼬子文档 field.id 给出未定义【英文标题】:mongoose subdocument field.id giving undefined 【发布时间】: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
我尝试了很多,但效果不佳:( 请帮帮我...
【问题讨论】:
【参考方案1】:您需要更改批次和标记架构:
const BatchSchema = new Schema(
student_base_no:
type: mongoose.SchemaTypes.ObjectId,
required: false,
,
results:
type: Schema.Types.ObjectId,
ref: 'results'
)
【讨论】:
以上是关于猫鼬子文档 field.id 给出未定义的主要内容,如果未能解决你的问题,请参考以下文章
当我想在猫鼬中从数据库中查找文档时,函数返回未定义 [重复]