Node.js   发布时间:2022-04-24  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了node.js – mongoose填充不填充数组大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我面临的问题是mongoose查询没有填充数组类型.

这是学院架构

'use Strict';

var mongoose = require('mongoose');
var scheR_147_11845@a = mongoose.scheR_147_11845@a;

var InstitutescheR_147_11845@a = new scheR_147_11845@a({
    name: String,address: String,city: String,country: String,zip: String,@R_674_11125@r: { type: mongoose.scheR_147_11845@a.objectId,ref: 'User' },teachers: [{type: mongoose.scheR_147_11845@a.objectId,ref: 'Teacher'}],categories: [String],created : { type : Date,default : Date.Now }
});

module.exports = mongoose.model('Institute',InstitutescheR_147_11845@a);

这是教师scheR_147_11845@a

'use Strict';

var mongoose = require('mongoose');
var scheR_147_11845@a = mongoose.scheR_147_11845@a;

var TeacherscheR_147_11845@a = new scheR_147_11845@a({
    education: [{degree: String,institutename: String}],dob: Date,photoUrl: String,phonenumber: String,@R_674_11125@r: {type: mongoose.scheR_147_11845@a.objectId,ref: 'User'},institutes: [{type: mongoose.scheR_147_11845@a.objectId,ref: 'Institute'}],subjects: [{type: mongoose.scheR_147_11845@a.objectId,ref: 'Subject'}],default : Date.Now }
})

module.exports = mongoose.model('Teacher',TeacherscheR_147_11845@a);

这是一种按所有者ID查询学院的方法

exports.mine = function (req,res,next) {
    var ObjectId = mongoose.Types.ObjectId;
    var userId = new ObjectId(req.user._id);
    Institute.find({
        @R_674_11125@r: userId
    }).populate('teachers').exec(function (err,institutE) {
        if (err) return next(err);
        if (!institutE) return res.json(401);
        res.json(institutE);
    });
};

我可以从数据库中看到该机构已经添加了老师

db.institutes.find();
{ 
    "_id" : ObjectId("554719a9f5be11c6d4369264"),"@R_674_11125@r" : ObjectId("5547199bf5be11c6d4369263"),"country" : "USA","name" : "Raghvendra Singh","address" : "38589 Royal Ann Cmn","city" : "Fremont","zip" : "94536","created" : ISODate("2015-05-04T07:03:05.569Z"),"categories" : [ "IIT","MeDical" ],"teachers" : [ ObjectId("55471965f5be11c6d436925f") ],"__v" : 3 
}

不知何故,查询方法不会填充教师集合.奇怪的是,我甚至没有得到对象id的集合,它返回并建立空教师阵列.

当我从方法调用删除.populate(‘teachers’)时,它确实返回带有对象id的教师数组.

我查看了文档,我看不出我做错了什么.

解决方法

首先,您需要稍微改变您的模型,如教师费用所述.

teachers: [ { teacher: { type: scheR_147_11845@a.objectId,ref: "Teacher" } } ]

exports.mine = function (req,next) {
    var ObjectId = mongoose.Types.ObjectId;
    var userId = new ObjectId(req.user._id);
    Institute.find({
        @R_674_11125@r: userId
    }).populate('**teachers.teacher**').exec(function (err,institutE) {
        if (err) return next(err);
        if (!institutE) return res.json(401);
        res.json(institutE);
    });
};

然后,将您的populate参数更改为teachers.teacher.它会工作

大佬总结

以上是大佬教程为你收集整理的node.js – mongoose填充不填充数组全部内容,希望文章能够帮你解决node.js – mongoose填充不填充数组所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。