mongoose 子文档 field.id 未定义
mongoose subdocument field.id giving undefined
在这段代码中,我需要 batch_results 使用其生成的 ID,如中所述
猫鼬文档
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)
但它一直说无法读取未定义的属性'id'
我试了很多但都不好:(
请帮帮我...
您需要更改批处理和标记架构:
const BatchSchema = new Schema({
student_base_no: {
type: mongoose.SchemaTypes.ObjectId,
required: false,
},
results:{
type: Schema.Types.ObjectId,
ref: 'results'
}
})
在这段代码中,我需要 batch_results 使用其生成的 ID,如中所述 猫鼬文档
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)
但它一直说无法读取未定义的属性'id'
我试了很多但都不好:( 请帮帮我...
您需要更改批处理和标记架构:
const BatchSchema = new Schema({
student_base_no: {
type: mongoose.SchemaTypes.ObjectId,
required: false,
},
results:{
type: Schema.Types.ObjectId,
ref: 'results'
}
})