mongoose Mongodb:使用子文档填充查询,并执行相反的操作

ttp71kqs  于 9个月前  发布在  Go
关注(0)|答案(1)|浏览(101)

我有一个教室的架构

const Schema_CLASSI = mongoose.Schema({
    course: {
        type: String,
        required: false
    },
    date: {
        type: Date,
        default: Date.now
    }
});

和学生的图式:

const Schema_ALUNNI = mongoose.Schema({
    classe_id: { type: Schema.Types.ObjectId, ref: 'CLASSI_collezione' },
    nome: {
        type: String,
        required: false
    }
});

我如何查询和获得这样的列表
1班学生_1班学生_2班学生_3班学生_4班学生_5班学生_6班学生_3班学生_7
这是一个像人口一样的现象,但我找不到解决办法。

qf9go6mv

qf9go6mv1#

让我试着弄明白你想干什么

const Schema_CLASSI = mongoose.Schema({
    course: {
        type: String,
        required: false
    },
    date: {
        type: Date,
        default: Date.now
    }
});

那你是说我的学生收藏有很多课程的链接

const Schema_ALUNNI = mongoose.Schema({
    classe_id: { type: Schema.Types.ObjectId, ref: 'CLASSI_collezione' },
    nome: {
        type: String,
        required: false
    }
});

解决办法是让每个班级都有一组学生

const Schema_CLASSI = mongoose.Schema({
    course: {
        type: String,
        required: false
    },
    date: {
        type: Date,
        default: Date.now
    }
   student_ids: [{ type: Schema.Types.ObjectId, ref: 'CLASSI_collezione' }],
});

一对多关系
请记住,填充不是特别有效的方法,您可以查看聚合https://www.mongodb.com/docs/manual/reference/operator/aggregation/lookup/
您还可以使用子文档方法
https://www.mongodb.com/docs/v5.0/tutorial/model-embedded-one-to-many-relationships-between-documents/
希望它能帮助
巴林特

相关问题