我正在try 合并和邮箱和电话号码为用户返回的单个文档,这是从其他两个文档获得.我有一条"几乎"管用的管路...但这并不完全正确.
以下是我的方案:
用户
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const 用户Schema = new Schema({
fName: { type: String, required: true },
lName: { type: String, required: true },
});
module.exports = 用户 = mongoose.model('users', 用户Schema);
一些用户数据:
{
"_id":"65d7e9a82bd4a4e423570962",
"fName": "Mike",
"lName": "Liss",
}
用户 联系人信息架构
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// create the schema
const 用户ContactInfoSchema = new Schema({
REF_用户ID: { type: Schema.Types.ObjectId, required: true, ref: 'users' },
REF_ContactInfoID: { type: Schema.Types.ObjectId, required: true, ref: 'contactinfos' },
});
module.exports = 用户ContactInfo = mongoose.model('usercontactinfos', 用户ContactInfoSchema);
用户联系人信息数据:
{
"_id": "65d7e9a82bd4a4e423570965",
"REF_用户ID": "65d7e9a82bd4a4e423570962",
"REF_ContactInfoID":"65d7e9a72bd4a4e423570959"
},
{
"_id":"65d7e9a92bd4a4e42357096a",
"REF_用户ID":"65d7e9a82bd4a4e423570962",
"REF_ContactInfoID":"65d7e9a82bd4a4e42357095e"
}
联系人信息架构
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// create the schema
const ContactInfoSchema = new Schema({
value: { type: String, required: true },// either phone number or email
type: { type: Number, required: true },
});
module.exports = ContactInfo = mongoose.model('contactinfos', ContactInfoSchema);
联系人数据:
{
"_id": "65d7e9a72bd4a4e423570959",
"value": "michael.liss@live.com",
"type": 0
},
{
"_id":"65d7e9a82bd4a4e42357095e",
"value": "5102071234",
"type": 1
}
以下是我的渠道:
[
{
$lookup: {
from: "usercontactinfos",
localField: "_id",
foreignField: "REF_用户ID",
as: "uci",
},
},
{
$unwind: {
path: "$uci",
preserveNullAndEmptyArrays: true,
},
},
{
$lookup: {
from: "contactinfos",
localField: "uci.REF_ContactInfoID",
foreignField: "_id",
as: "ci",
},
},
{
$unwind: {
path: "$ci",
preserveNullAndEmptyArrays: true,
},
},
{
$project: {
_id: 1,
fName: 1,
lName: 1,
email: {
$cond: {
if: {
$eq: ["$ci.type", 0],
},
then: "$ci.value",
else: null,
},
},
phone: {
$cond: {
if: {
$eq: ["$ci.type", 1],
},
then: "$ci.value",
else: null,
},
},
},
},
{
$group: {
_id: "$_id",
fName: {
$first: "$fName",
},
lName: {
$first: "$lName",
},
email: {
$first: "$email",
},
phone: {
$first: "$phone",
},
},
},
]
我得到的是:
{
"_id": "65d7e9a82bd4a4e423570962",
"fName": "Mike",
"lName": "Liss",
"email": "michael.liss@live.com",
"phone": "michael.liss@live.com"
}
我想要实现的目标是:
{
"_id": "65d7e9a82bd4a4e423570962",
"fName": "Mike",
"lName": "Liss",
"email": "michael.liss@live.com",
"phone": "510-207-1234"
}