1

I am using Nodejs and MongoDB with expressjs and mongoose library, creating a Blog API having users, articles & comments schema. Below are schemas that I use.

const UsersSchema = new mongoose.Schema({
    username:        { type: String },
    email:           { type: String },
    date_created:    { type: Date },
    last_modified:   { type: Date }
});    




const ArticleSchema = new mongoose.Schema({
    id:              { type: String, required: true },
    text:            { type: String, required: true }, 
    posted_by:       { type: Schema.Types.ObjectId, ref: 'User', required: true },
    images:          [{ type: String }],
    date_created:    { type: Date },
    last_modified:   { type: Date }
});




const CommentSchema = new mongoose.Schema({
    id:             { type: String, required: true },
    commented_by:   { type: Schema.Types.ObjectId, ref: 'User', required: true },
    article:        { type: Schema.Types.ObjectId, ref: 'Article' },
    text:           { type: String, required: true },
    date_created:   { type: Date },
    last_modified:  { type: Date } 
});

1 Answer 1

2

You can use below $lookup aggregation from mongodb 3.6 and above

Article.aggregate([
  { "$match": { "posted_by": mongoose.Types.ObjectId(id) } },
  { "$lookup": {
    "from": Comment.collection.name,
    "let": { "id": "$_id" },
    "pipeline": [
      { "$match": { "$expr": { "$eq": [ "$article", "$$id" ] } } }
    ],
    "as": "comments"
  }},
  { "$addFields": {
    "comments_no": { "$size": "$comments" },
    "hasCommented": { "$in": [mongoose.Types.ObjectId(id), "$comments.commented_by"] }
  }}
])
Sign up to request clarification or add additional context in comments.

4 Comments

Ok then remove the $match stage if you want to get the data for all the users. it is not returning the exact number of comment It should not happen
Yes, it is working but when MongoDB Replicaset is enabled. if it is enabled, you will not be able to use some aggregation functionality including $lookup so be careful.
@GorKotikyan The restriction on $lookup (as at MongoDB 4.0) is that the from collection must be unsharded and in the same database -- you can still use the $lookup command in a replica set or sharded environment. For expanded support there is a relevant feature request you can watch/upvote in the MongoDB issue: SERVER-29159: Add $lookup support for sharded collections.
Hello, @AnthonyWinzlet can you help me on this question? stackoverflow.com/q/54376551/9159002

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.