节点查找未返回聚合数据

时间:2018-10-22 08:44:14

标签: node.js mongodb aggregate lookup

我的Node App中有2个集合用于约会和客户,我想显示约会以及与约会相关的用户。我已经进行了如下设置,但是没有得到用户的输出。

new PrintWriter(s.getOutoutStream()) 

我的查询查询是:-

var userSchema = new mongoose.Schema({
 firstname: String,
 surname: String,
 email: String,
});

var appointmentSchema = new mongoose.Schema({
 userID: String,
 type: Number,
 time: Date
});

mongo中的数据在这里,约会数据:-

Appointment.aggregate([
    {
        $match: {"type": 1}  
    },
    {
        $lookup:{
            from: "users",
            localField: "userID",
            foreignField: "_id",
            as: "appointmentUser"
        } 
    }
], function(err,foundAppointmentUser) {
        if(err){
            console.log(err);
        } else {
            console.log(foundAppointmentUser);
        }
    });

用户数据:

{
    "_id": {
        "$oid": "5bcc8eac7ac5980bfa365183"
    },
    "userID": "5bb4d1945480e60771ccde5a",
    "type": 1,
    "time": {
        "$date": "2018-10-22T10:00:00.000Z"
    },
    "__v": 0
}

这是结果:-

{
    "_id": {
        "$oid": "5bb4d1945480e60771ccde5a"
    },
    "firstname": "Stu",
    "surname": "Test 999",
    "email": "stu@stu.com",
    "created": {
        "$date": "2018-10-03T14:26:28.815Z"
    },
    "__v": 0
}

这是检索此类数据的最佳方法吗?为什么我没有在[ { _id: 5bcc8eac7ac5980bfa365183, userID: '5bb4d1945480e60771ccde5a', type: 1, time: 2018-10-22T10:00:00.000Z, __v: 0, appointmentUser: [] } ] 数组下接收用户数据?预先感谢。

1 个答案:

答案 0 :(得分:0)

按如下所示更改架构:仅供参考,Populate

var appointmentSchema = new mongoose.Schema({
 userID: {
   type: Schema.Types.ObjectId,
   ref: 'user'
 },
 type: Number,
 time: Date
});

参考ID (UserId)的类型应为ObjectId,而不是String