我正在查询有关猫鼬聚合的问题。我一直在尝试获取用户详细信息以及喜欢和喜欢的人数以及它们之间的关系,但我无法成功。
这是我的情况,我有一个用户表和反应表。用户表保存用户详细信息,反应表包含用户详细信息以及其他信息,例如喜欢用户的用户。在我的架构中,其类型为:type ='like'或love,因此我需要获取用户详细信息以及喜欢的次数。我是MongoDB的新手。
这是我的代码:
用户架构
// Importing Node packages required for schema
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const validateEmail = function(email) {
const re = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
return re.test(email)
};
//= ===============================
// User Schema
//= ===============================
const UserSchema = new Schema({
email: {
type: String,
trim: true,
lowercase: true,
},
reactions : [
{ type: Schema.Types.ObjectId, ref: 'ProfileReaction' }
],
},
{
timestamps: true
}
);
module.exports = mongoose.model('User', UserSchema);
反应模式
const mongoose = require('mongoose'),
Schema = mongoose.Schema;
const ProfileReactionSchema = new Schema({
likedBy: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true,
index: true
},
user: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true,
index: true
},
type: {
type: String,
required: true,
},
},
{
timestamps: true // Saves createdAt and updatedAt as dates. createdAt will be our timestamp.
}
);
module.exports = mongoose.model('ProfileReaction', ProfileReactionSchema);
我真正想要的是下面的东西
{
_id: '1234',
email: 'xyz@gmail.com',
reactions: [
{
_id: '1235',
likedBy: {...},
user: {...},
type: 'like'
},
{
_id: '1236',
likedBy: {...},
user: {...},
type: 'love'
}
],
noOfLikes: 1,
noOfLoves: 1
}
到目前为止,我一直在尝试,但这只是给我提供了联系,而我没有得到喜欢和爱的数目。但是我需要他们两个都喜欢伯爵,爱伯爵和关系
const user = await User.findOne({$or: [
req.params.id.match(/^[0-9a-fA-F]{24}$/) ? {_id: mongoose.Types.ObjectId(req.params.id)}
: {uid: req.params.id}
]}).populate([
{
path: 'reactions',
model: 'ProfileReaction',
populate: [
{
path: 'likedBy',
model: 'User'
}
]
}
]);
我正在使用mongoose v5.6.10
版。
答案 0 :(得分:1)
您可以使用下面的$lookup
聚合
User.aggregate([
{ "$match": {
"$or": [
req.params.id.match(/^[0-9a-fA-F]{24}$/)
? { "_id": mongoose.Types.ObjectId(req.params.id) }
: { "uid": req.params.id }
]
}},
{ "$lookup": {
"from": ProfileReaction.collection.name,
"let": { "reactions": "$reactions" },
"pipeline": [
{ "$match": {
"$expr": { "$in": ["$_id", "$$reactions"] },
"type": "like"
}}
],
"as": "likeReactions"
}},
{ "$lookup": {
"from": ProfileReaction.collection.name,
"let": { "reactions": "$reactions" },
"pipeline": [
{ "$match": {
"$expr": { "$in": ["$_id", "$$reactions"] },
"type": "love"
}}
],
"as": "loveReactions"
}},
{ "$addFields": {
"noOfLikes": { "$size": "$likeReactions" },
"noOfLoves": { "$size": "$loveReactions" }
}}
])