使用猫鼬“填充"时遇到问题 [英] Trouble using mongoose 'Populate'

查看:61
本文介绍了使用猫鼬“填充"时遇到问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

早上好,

所以我似乎在用 Node.js 和 Mongoose 填充我的字段时遇到了问题.它只是打开一个空白数组:

结果:(JSON)

<预><代码>[{课程作业":[],"_id": "5db56ceb4cc2c92824ae2651","name": "加里波第","网站": "www.garibaldi.org.uk",__v":0},{课程作业":[],"_id": "5db56d074cc2c92824ae2652","name": "柯克哈勒姆","网站": "www.kirkhallamacademy.co.uk",__v":0}]

下面是我使用的调用 populate 函数的代码,以及我为每个数据使用的模型.很奇怪.

*school.js(模型)*

//需要我们文件中的模块:const 猫鼬 = 要求('猫鼬')const schoolSchema = new mongoose.Schema({名称: {类型:字符串,要求:真实,独特:真实,修剪:真实},网站: {类型:字符串,要求:真实,修剪:真实},商标: {类型:缓冲器},课程作业:[{类型:mongoose.Schema.Types.ObjectID,参考:'课程分配'}]})//导出用户以在其他文件中使用:const school = mongoose.model('School', schoolSchema)module.exports = 学校

courseassignment.js(模型)

//需要我们文件中的模块:const 猫鼬 = 要求('猫鼬')const courseAssignmentSchema = new mongoose.Schema({学校: {类型:mongoose.Schema.Types.ObjectID,要求:真实,参考:'学校'},课程: {类型:mongoose.Schema.Types.ObjectID,要求:真实,参考:'课程'}})//导出用户以在其他文件中使用:const courseAssignment = mongoose.model('CourseAssignment', courseAssignmentSchema)module.exports = courseAssignment

* 获取数据的代码:(在 app.js 中)*

router.get('/school', async (req, res) => {const school = await School.find({}).populate({ path: 'courseassignments' })res.send(学校)})

解决方案

我会从 School 模型中删除 courseassignment ref,并会利用虚拟人口.

以下是步骤:

  • school.js(学校模型 - 如您所见,我删除了 courseassignments 引用,并添加了虚拟功能选项)

const mongoose = require('mongoose')const schoolSchema = new mongoose.Schema({名称: {类型:字符串,要求:真实,独特:真实,修剪:真实},网站: {类型:字符串,要求:真实,修剪:真实},商标: {类型:缓冲器}}, {toJSON: { virtuals: true },toObject:{虚拟:真实}})schoolSchema.virtual(课程作业",{参考:课程分配",外国字段:学校",本地字段:_id"})const school = mongoose.model('School', schoolSchema)module.exports = 学校

此时,当您到达学校端点时,您的响应将是这样的.(我只显示一个项目很短.)

<预><代码>[{"_id": "5db5a809cfc9951770d5078a","name": "学校 1","网站": "学校 1 网站","__v": 0,课程作业":[{"_id": "5db5a892cfc9951770d50790","学校": "5db5a809cfc9951770d5078a","课程": "5db5a847cfc9951770d5078d",__v":0},{"_id": "5db5a89ccfc9951770d50791","学校": "5db5a809cfc9951770d5078a","课程": "5db5a851cfc9951770d5078e",__v":0},{"_id": "5db5a8a1cfc9951770d50792","学校": "5db5a809cfc9951770d5078a","课程": "5db5a858cfc9951770d5078f",__v":0}],"id": "5db5a809cfc9951770d5078a"},......]

如果您还想访问课程名称(我认为这很好),

  • courseassigment.js

const mongoose = require('mongoose')const courseAssignmentSchema = new mongoose.Schema({学校: {类型:mongoose.Schema.Types.ObjectID,要求:真实,参考:'学校'},课程: {类型:mongoose.Schema.Types.ObjectID,要求:真实,参考:'课程'}}, {toJSON: { virtuals: true },toObject:{虚拟:真实}})courseAssignmentSchema.pre(/^find/, function (next) {this.populate({路径:'课程'});下一个();});//可能需要这样的索引//courseAssignmentSchema.index({ school: 1, course: 1 }, { unique: true });const courseAssignment = mongoose.model('CourseAssignment', courseAssignmentSchema)module.exports = courseAssignment

这样,结果将包含课程相关字段,如课程名称.

<代码>[[{"_id": "5db5a809cfc9951770d5078a","name": "学校 1","网站": "学校 1 网站","__v": 0,课程作业":[{"_id": "5db5a892cfc9951770d50790","学校": "5db5a809cfc9951770d5078a",课程": {"_id": "5db5a847cfc9951770d5078d","name": "课程 1",__v":0},"__v": 0,id":5db5a892cfc9951770d50790"},{"_id": "5db5a89ccfc9951770d50791","学校": "5db5a809cfc9951770d5078a",课程": {"_id": "5db5a851cfc9951770d5078e","name": "课程 2",__v":0},"__v": 0,id":5db5a89ccfc9951770d50791"},{"_id": "5db5a8a1cfc9951770d50792","学校": "5db5a809cfc9951770d5078a",课程": {"_id": "5db5a858cfc9951770d5078f","name": "课程 3",__v":0},"__v": 0,id":5db5a8a1cfc9951770d50792"}],"id": "5db5a809cfc9951770d5078a"},......]

文档:

https://mongoosejs.com/docs/tutorials/virtuals.html

https://mongoosejs.com/docs/populate.html#populate-virtuals

Good Morning,

So I seem to have an issue with populating my fields with Node.js and Mongoose. It is just turning up a blank array:

Result: (JSON)

[
    {
        "courseassignments": [],
        "_id": "5db56ceb4cc2c92824ae2651",
        "name": "Garibaldi",
        "website": "www.garibaldi.org.uk",
        "__v": 0
    },
    {
        "courseassignments": [],
        "_id": "5db56d074cc2c92824ae2652",
        "name": "Kirk Hallam",
        "website": "www.kirkhallamacademy.co.uk",
        "__v": 0
    }
]

Below is the code I am using the call the populate function, plus the models that I am using for each of the data. It is very weird.

*school.js (Model) *

// Require modules within our file:
const mongoose = require('mongoose')

const schoolSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true,
        unique: true,
        trim: true
    },
    website: {
        type: String,
        required: true,
        trim: true
    },
    logo: {
        type: Buffer
    },
    courseassignments: [{
        type: mongoose.Schema.Types.ObjectID, 
        ref: 'CourseAssignment'
    }]
})

// Export the user to use within other files:
const school = mongoose.model('School', schoolSchema)
module.exports = school

courseassignment.js (Model)

// Require modules within our file:
const mongoose = require('mongoose')

const courseAssignmentSchema = new mongoose.Schema({
    school: {
        type: mongoose.Schema.Types.ObjectID,
        required: true,
        ref: 'School'
    },
    course: {
        type: mongoose.Schema.Types.ObjectID,
        required: true,
        ref: 'Course'
    }
})

// Export the user to use within other files:
const courseAssignment = mongoose.model('CourseAssignment', courseAssignmentSchema)
module.exports = courseAssignment

* Code to fetch data: (within app.js)*

router.get('/school', async (req, res) => {

    const schools = await School.find({}).populate({ path: 'courseassignments' })
    res.send(schools)

})

解决方案

I would remove the courseassigment ref from the School model, and would take advantage of virtual populate.

So here are the steps:

  • school.js (school model - as you see I removed courseassignments ref, and added options for virtual features)

const mongoose = require('mongoose')

const schoolSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true,
        unique: true,
        trim: true
    },
    website: {
        type: String,
        required: true,
        trim: true
    },
    logo: {
        type: Buffer
    }
}, {
    toJSON: { virtuals: true },
    toObject: { virtuals: true }
})

schoolSchema.virtual("courseassignments", {
    ref: "CourseAssignment",
    foreignField: "school",
    localField: "_id"
})

const school = mongoose.model('School', schoolSchema)
module.exports = school

At this point when you hit the schools endpoint, your response will be like this. ( I only show one item to be short.)

[
    {
        "_id": "5db5a809cfc9951770d5078a",
        "name": "school 1",
        "website": "school 1 website",
        "__v": 0,
        "courseassignments": [
            {
                "_id": "5db5a892cfc9951770d50790",
                "school": "5db5a809cfc9951770d5078a",
                "course": "5db5a847cfc9951770d5078d",
                "__v": 0
            },
            {
                "_id": "5db5a89ccfc9951770d50791",
                "school": "5db5a809cfc9951770d5078a",
                "course": "5db5a851cfc9951770d5078e",
                "__v": 0
            },
            {
                "_id": "5db5a8a1cfc9951770d50792",
                "school": "5db5a809cfc9951770d5078a",
                "course": "5db5a858cfc9951770d5078f",
                "__v": 0
            }
        ],
        "id": "5db5a809cfc9951770d5078a"
    },
    ...
    ...
]

And if you also want to access to the Course name (which I think would be good),

  • courseassigment.js

const mongoose = require('mongoose')

const courseAssignmentSchema = new mongoose.Schema({
    school: {
        type: mongoose.Schema.Types.ObjectID,
        required: true,
        ref: 'School'
    },
    course: {
        type: mongoose.Schema.Types.ObjectID,
        required: true,
        ref: 'Course'
    }
}, {
    toJSON: { virtuals: true },
    toObject: { virtuals: true }
})

courseAssignmentSchema.pre(/^find/, function (next) {

    this.populate({
        path: 'course'
    });
    next();
});


// an index may be required like this
//courseAssignmentSchema.index({ school: 1, course: 1 }, { unique: true });

const courseAssignment = mongoose.model('CourseAssignment', courseAssignmentSchema)
module.exports = courseAssignment

And with this the result will contain the course related fields like course name.

[[
    {
        "_id": "5db5a809cfc9951770d5078a",
        "name": "school 1",
        "website": "school 1 website",
        "__v": 0,
        "courseassignments": [
            {
                "_id": "5db5a892cfc9951770d50790",
                "school": "5db5a809cfc9951770d5078a",
                "course": {
                    "_id": "5db5a847cfc9951770d5078d",
                    "name": "course 1",
                    "__v": 0
                },
                "__v": 0,
                "id": "5db5a892cfc9951770d50790"
            },
            {
                "_id": "5db5a89ccfc9951770d50791",
                "school": "5db5a809cfc9951770d5078a",
                "course": {
                    "_id": "5db5a851cfc9951770d5078e",
                    "name": "course 2",
                    "__v": 0
                },
                "__v": 0,
                "id": "5db5a89ccfc9951770d50791"
            },
            {
                "_id": "5db5a8a1cfc9951770d50792",
                "school": "5db5a809cfc9951770d5078a",
                "course": {
                    "_id": "5db5a858cfc9951770d5078f",
                    "name": "course 3",
                    "__v": 0
                },
                "__v": 0,
                "id": "5db5a8a1cfc9951770d50792"
            }
        ],
        "id": "5db5a809cfc9951770d5078a"
    },
    ...
    ...
]

Docs:

https://mongoosejs.com/docs/tutorials/virtuals.html

https://mongoosejs.com/docs/populate.html#populate-virtuals

这篇关于使用猫鼬“填充"时遇到问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆