0

I have the category schema like this:

var category_article_Schema = new Schema({
    "article_id": { type: String, required: false, unique: false },
    "category": String,
    "articles": [{ type: mongoose.Schema.Types.ObjectId, ref:'article'}],
});

var category_article_Schema = mongoose.model('category_article_Schema', category_article_Schema);
module.exports = category_article_Schema;

Article schema:

var articleSchema = new Schema({
    "title": { type: String, required: true, unique: false },
    "details": String,
    "username": { type: String, required: true, unique: false },
    "postImageUrl": String,
    "url": String,
    "categories": [String],
    "created_at": { type: Date, default: Date.now }
});

var article = mongoose.model('article', articleSchema);
module.exports = article;

When I try to populate articles in the below function, I get only category id and name but no articles populated.

function getPostByCategory(req, res, next) {
    category_article_model.find({category: req.params.name}) //sports
    .populate('articles')
    .exec()
    .then(function(articlesByCategory) {
        console.log(articlesByCategory);
    })
    .catch(function(err){
        console.log('err ', err);
    })
}

All the data I have in article collection is this:

`{
    "_id": {
        "$oid": "5b0008ce8787890004989df1"
    },
    "categories": [
        "sports",
        "health"
    ],
    "title": "sample",
    "details": "sample ",
    "created_at": {
        "$date": "2018-05-19T11:21:50.837Z"
    },
    "__v": 0
},

{
    "_id": {
        "$oid": "5b0087646dda9600049a9a27"
    },
    "categories": [
        "sports"
    ],
    "title": "sample3333",
    "details": " sample3333",
    "created_at": {
        "$date": "2018-05-19T20:21:56.126Z"
    },
    "__v": 0
}`

And category_article_schema collection has:

{
    "_id": {
        "$oid": "5b0087646dda9600049a9a28"
    },
    "category": "sports",
    "article_id": "5b0087646dda9600049a9a27",
    "__v": 0
}

But the data returned is empty array of article:

[ { articles: [],
_id: 5b0008ce8787890004989df2,
category: 'sports',
article_id: '5b0008ce8787890004989df1',
__v: 0 } ]

I am not sure what could be the issue?

kittu
  • 6,662
  • 21
  • 91
  • 185
  • How adding document to `category_article_Schema` collection? It seems you are not saving any `_id` of `article` in the `articles` array – PaulShovan May 19 '18 at 21:26
  • `"article_id": "5b0087646dda9600049a9a27",` is a "string" and not an `ObjectId`, so they do not match. The question also appears to be exactly the same as: [lookup join in mongoose returns empty array](https://stackoverflow.com/q/50425398/2313887) also marked as a duplicate and marked to the same problem of coverting the values. Additionally marked to included the additional "category" constraints. – Neil Lunn May 19 '18 at 22:47

0 Answers0