mongodb Mongoose无法填充嵌套项

a14dhokn  于 2023-08-04  发布在  Go
关注(0)|答案(1)|浏览(131)

我使用的是express + mongoose,一般来说,populate方法工作得很好。然而,有一种情况,它不起作用。它也不会显示任何错误:
我有一个任务模型,它有一些模块:

import { Model, Schema, model } from 'mongoose';
import { IAssignment } from '../interfaces/app/IAssignment';

// Define Mongoose schema for Assignment
const AssignmentSchema = new Schema<IAssignment>(
  {
    name: { type: String, trim: true, required: true },
    modules: [
      {
        module: { type: Schema.Types.ObjectId, ref: 'AssignmentModule' },
        dueDate: { type: Date },
      },
    ],
  },
);

// Create and export Mongoose model
const Assignment: Model<IAssignment> = model<IAssignment>(
  'Assignment',
  AssignmentSchema
);

export default Assignment;

字符串
AssignmentModule还有另一个模型

import { IAssignmentModule } from '../interfaces/app/IAssignmentModule';
const Schema = mongoose.Schema;

// Define Mongoose schema for Module
const AssignmentModuleSchema = new Schema<IAssignmentModule>(
  {
    title: { type: String },
    questions: [{ type: Schema.Types.ObjectId, ref: 'Question' }],
  },
  { timestamps: true, versionKey: false }
);

// Create and export Mongoose model
const AssignmentModule: Model<IAssignmentModule> =
  mongoose.model<IAssignmentModule>('AssignmentModule', AssignmentModuleSchema);
export default AssignmentModule;


这是我的控制器函数,它应该给予我所有填充了modules.module的赋值。

const assignments: IAssignment[] = await Assignment.find().populate([
      { path: 'modules', populate: 'modules.module' },
    ]);


我的最终目标是填充模块。模块,然后在模块内部,还有一个问题参考,需要填充一些选定的字段,比如namescore。我知道我可以链接人口,但我的第一个人口本身并没有发生。将您的字段命名为模块是否有任何问题?还是这里还缺了什么?

bzzcjhmw

bzzcjhmw1#

modules是子文档,请参见Alternate declaration syntax for array。填充路径应为modules.module
例如:

import mongoose from 'mongoose';
import util from 'util';
import { config } from '../../config';

mongoose.set('debug', true);
console.log(mongoose.version);

const QuestionSchema = new mongoose.Schema({
    score: Number,
});
const Question = mongoose.model('Question', QuestionSchema);

const AssignmentModuleSchema = new mongoose.Schema({
    title: { type: String },
    questions: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Question' }],
});
const AssignmentModule = mongoose.model('AssignmentModule', AssignmentModuleSchema);

const AssignmentSchema = new mongoose.Schema({
    modules: [
        {
            module: { type: mongoose.Schema.Types.ObjectId, ref: 'AssignmentModule' },
            dueDate: { type: Date },
        },
    ],
});
const Assignment = mongoose.model('Assignment', AssignmentSchema);

(async function main() {
    try {
        await mongoose.connect(config.MONGODB_URI);
        await Promise.all([Question, Assignment, AssignmentModule].map((m) => m.collection.drop()));
        // seed
        const [q1] = await Question.create([{ score: 100 }, { score: 80 }]);
        const [m1] = await AssignmentModule.create([{ title: 'a', questions: [q1] }, { title: 'b' }]);
        await Assignment.create([{ modules: [{ module: m1, dueDate: Date.now() }] }, { modules: [] }]);

        // test
        const assignmentDocs = await Assignment.find().populate({
            path: 'modules.module',
            select: '-__v',
            populate: { path: 'questions', select: '-__v' },
        });
        console.log(util.inspect(assignmentDocs, false, null));
    } catch (error) {
        console.error(error);
    } finally {
        await mongoose.connection.close();
    }
})();

字符串
调试日志:

[
  {
    _id: new ObjectId("64a807003389777bbfe22f2f"),
    modules: [],
    __v: 0
  },
  {
    _id: new ObjectId("64a807003389777bbfe22f2d"),
    modules: [
      {
        module: {
          _id: new ObjectId("64a807003389777bbfe22f29"),
          title: 'a',
          questions: [
            {
              _id: new ObjectId("64a807003389777bbfe22f25"),
              score: 100
            }
          ]
        },
        dueDate: 2023-07-07T12:37:20.672Z,
        _id: new ObjectId("64a807003389777bbfe22f2e")
      }
    ],
    __v: 0
  }
]

相关问题