Mongoose populate返回null

时间:2017-11-21 06:36:48

标签: mongodb express mongoose

我一直在寻找这个好几个小时。但是这些解决方案都没有用,或者是我。

我有两个模特。

文章:

const mongoose = require("mongoose");

const Schema = mongoose.Schema;

const articlesSchema = new Schema({
    articleHeader: String,
    articleBody: String,
    byUserId: {type: Schema.Types.ObjectId, ref: 'user'},
    additionDate: Date,
});

module.exports = mongoose.model('articles', articlesSchema, 'ArticlesInfo');

用户:

const mongoose = require("mongoose");

const Schema = mongoose.Schema;

const userSchema = new Schema({
    fname: String,
    lname: String,
    email: String,
    pwd: String,
    dob: Date,
    gender: String,     
});

module.exports = mongoose.model('user', userSchema, 'UserInfo');

我的查询是这样的:

router.get('/articles', function(req,res){

    article.find().populate("byUserId").sort({"additionDate": -1}).exec(function(err, articl) {
        if(err) {
            res.send("Error! " + err);
        } else {
            console.log(articl);
            res.json(articl);
        }
    });

});

但我的输出总是:

    {
        "_id": "5a13254a081af40d6c55654e",
        "additionDate": "2017-11-20T18:56:10.951Z",
        "byUserId": null,
        "articleBody": "Body 1",
        "articleHeader": "Header 1",
        "__v": 0,
    }

当我删除populate时," byUserId"正在返回ObjectId。

0 个答案:

没有答案