MongoDB Aggregation, Mongodb Query - PullRequest
       14

MongoDB Aggregation, Mongodb Query

0 голосов
/ 24 января 2019

Я использую Nodejs и MongoDB с библиотекой expressjs и mongoose , создаю Блог API , имеющий пользователей , статьи & комментарии схема.Ниже приведены схемы, которые я использую.

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 Ответ

0 голосов
/ 24 января 2019

Вы можете использовать ниже $lookup агрегация из mongodb 3,6 и выше

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"] }
  }}
])
...