获取Node / Express中属于一个用户的所有帖子

时间:2016-11-22 03:16:02

标签: node.js express mongoose

我有2个型号User&如下所示,复活......在路由器(见下文)中,获取属于用户/创建者的所有复活以在其仪表板/个人资料页面上显示的查询是什么?

用户模型:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var userSchema = new Schema({
    firstName: {
        type: String,
        required: true
    },
    lastName: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true
    },
    password: {
        type: String,
        required: true
    }
});

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

Revive Model:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var reviveSchema = new Schema({
    reviveTitle: {
        type: String,
        required: true
    },
    reviveStory: {
        type: String
    },
    author: {
        id: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "User"
        }
    }
});

module.exports = mongoose.model('Revive', reviveSchema);

路由器:

router.get('/dashboard', isLoggedIn, function(req, res) {
   code ?? to get all revives that belong to the creator/user only ??
    res.render('users/dashboard', {currentUser: req.user});
});

1 个答案:

答案 0 :(得分:2)

好吧,我会以不同的方式设置Revive架构:

author: { type: mongoose.Schema.Types.ObjectId, ref: "User"}

然后你应该能够做一个正确的发现:

const Revive = mongoose.model('Revive');

router.get('/dashboard', isLoggedIn, function(req, res) {
    Revive.find({author:req.user._id}, (e, revives) => {
       // however you handle errors goes first
       res.render('users/dashboard', {currentUser: req.user, revives: revives});
    });
});