gpt4 book ai didi

node.js - NodeJS、MongoDB、$lookup 结果为空数组的聚合函数[]

转载 作者:太空宇宙 更新时间:2023-11-03 23:23:17 25 4
gpt4 key购买 nike

我的成绩模型是:

var mongoose = require("mongoose");
var Schema = mongoose.Schema;

var GradeSchema = new Schema({
gID: {type:Schema.Types.ObjectId,ref: 'People'},
grade: Number,
type: Number
}, {timestamps: true});

var Grade = mongoose.model('Grade', GradeSchema);
module.exports=Grade;

人员模型是:

var mongoose = require("mongoose");
var Schema = mongoose.Schema;

var PeopleSchema = new Schema({
_id: {type:Schema.Types.ObjectId,ref:'Grade' },
name: String,
lastName:String,
phone: String
},{timestamps: true});

var People = mongoose.model('People', PeopleSchema);

module.exports=People;

我的聚合查询是:

Grade.aggregate([

{$lookup:{ from: 'People', localField:'glD',
foreignField:'_id',as:'myCustomResut'}},
]).exec((err, result)=>{
if (err) {
console.log("error" ,err)
}
if (result) {
console.log(result);
}
});

** 但 myCustomResut 是空结果,如 myCustomResut []: **这段代码有什么问题?

[ { _id: 5a13e33e931f7561b85d0840, updatedAt: 2017-11-21T08:26:38.413Z, createdAt: 2017-11-21T08:26:38.413Z, gID: 5a13e33e931f7561b85d083f, grade: 20, type: 2, __v: 0, myCustomResut:: [] }, { _id: 5a13e78e4fac5b61ecdbd9ab, updatedAt: 2017-11-21T08:45:02.517Z, createdAt: 2017-11-21T08:45:02.517Z, gID: 5a13e78e4fac5b61ecdbd9aa, grade: 20, type: 2, __v: 0, myCustomResut:: [] } ]

最佳答案

检查您的收藏是否真的是人物。根据经验,我知道人们创建了一个大写字母的集合,但在他们的数据库中它是小写的。所以检查它是否不是 people 。这与 Mongoose 有关。因此,再次尝试聚合:

Grade.aggregate([

{$lookup:{ from: 'people', localField:'gID',
foreignField:'_id',as:'myCustomResut'}},
]).exec((err, result)=>{
if (err) {
console.log("error" ,err)
}
if (result) {
console.log(result);
}
});

在这里您定义了字段gID(大写i):

var GradeSchema = new Schema({ gID: {type:Schema.Types.ObjectId,ref: 'People'}

这里你写了glD(小写L):

{$lookup:{ from: 'People', localField:'glD'

我更新了上面的代码片段,因此请重试,并将集合设置为 Peoplepeople。但错误肯定是glD。这对我来说也很棘手,因为如果你这样阅读代码,看起来并不存在问题。当我去编辑答案时我才意识到这是错误的。

关于node.js - NodeJS、MongoDB、$lookup 结果为空数组的聚合函数[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47441657/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com