node.js - 获取属于一个用户的所有帖子并显示以传递给 View Node/Express/Mongoose

标签 node.js mongodb express mongoose

下面是User模型、Post模型和路由的代码。我需要查询数据库,然后通过路由器传递给 View 。我错过了什么?

用户模型:

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

帖子模型:

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

var postSchema = new Schema({
    postTitle: {
        type: String,
        required: true
    },
    postStory: {
        type: String
    },
    author: {
        id: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "User"
        },
        username: String
    }
});

module.exports = mongoose.model('Post', postSchema);

这是我正在尝试的路由器中的查询,但显然这不是要走的路...

我的 GET 路线:

router.get('/dashboard', isLoggedIn, function(req, res) {
    Post.find({author:req.user._id}, (err, posts) => {
       if(err) {
         console.log(err);
       } else {
         res.render('users/dashboard', {currentUser: req.user, posts: posts});
       }
    });
});

我在这里错过了什么?

最佳答案

您可能希望更改 find 查询以匹配以下行中的正确属性:

Post.find({author: req.user._id}, (err, posts) => {

成为:

Post.find({'author.id': req.user._id}, (err, posts) => {

阅读更多:http://mongoosejs.com/docs/2.7.x/docs/finding-documents.html

关于node.js - 获取属于一个用户的所有帖子并显示以传递给 View Node/Express/Mongoose,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40738972/

相关文章:

javascript - 如何使用 Node-express 将页面 B 通过表单发布的数据渲染到页面 A?

mongodb - 在 Mongodb 中,如何检查所有文档的值是否都是唯一的?

javascript - 如何在 express 中导出应用程序对象?

node.js - AWS API Gateway OPTIONS 请求返回 500 错误

javascript - 使用 Node.js 编辑 mysql 中的现有行

node.js - 此代码会导致套接字 io 中的竞争条件吗?

node.js - Node AJV 验证架构

json - mongoimport 无法从 JSON 文件加载 $uuid 字段

python - Mongodb 引擎和 Django 创建自定义 ObjectId

javascript - ExpressJS Promise 和 EventEmitter 之间明显的竞争条件