I want to fetch the result using $lookup having local fields as the array of _id as a string. But its not happening. I also tried by using _id.str but still no results.
db.posts.aggregate([
{
$addFields: {
TagCount: { $size: "$tags" }
}
},
{
$lookup:
{
from: "tags",
localField: "tags",
foreignField: "_id",
as: "tagList"
}
},
]));
The schema for Post Collection
const postSchema = new mongoose.Schema({
title: {
type: String,
required: true,
minlength: 10,
set: v => v.replace(/\s\s+/gi, ' '),
get: v => { console.log(v); return v.replace(/\s\s+/gi, ' '); }
},
content: {
type: String,
required: true
},
headerImage: {
type: String
},
tags: [{
type: mongoose.Schema.Types.ObjectId,
required: true,
validate: {
validator: function (v) {
return v.length > 0;
}
},
message: 'There must be one tag',
ref: 'tags'
}],
creationDate: { type: Date, default: Date.now }
});
Here is the tag Schema Collection
const tagSchema = new mongoose.Schema({
name: {
type: String,
required: true,
minlength: 3,
set: value => value.replace(/\s\s+/gi, ' '),
get: value => value.replace(/\s\s+/gi, ' ')
},
description: {
type: String
},
creationDate: {
type: Date,
default: Date.now
}
}, {
collection: 'tags'
});
Also, I tried other StackOverflow questions but I didn't find any solutions.
tags
schema as well? – ma_jafaritags
field inposts
to be an array ofDBRef
? – Joe