无法在mongoose中填充文章

时间:2018-05-19 20:38:38

标签: javascript node.js mongodb mongoose

我有类似这样的类别架构:

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;

文章架构:

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;

当我尝试在下面的函数中填充文章时,我只获得了类别ID和名称,但没有填充文章。

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);
    })
}

我在article集合中的所有数据都是:

`{
    "_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
}`

category_article_schema集合有:

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

但返回的数据是空文章:

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

我不确定会出现什么问题?

0 个答案:

没有答案
相关问题