我有一个用户架构和一个帖子架构,其中一个用户有很多帖子。我想返回用户在名为'/ post / dashboard'的路线上的所有帖子。
这是我的模式:
let UserSchema = new Schema({
username: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
default: null,
},
profile_pic: {
type: String,
default: '/img/profilepic.png',
},
posts: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Post'
}
})
let PostSchema = new Schema({
title: {
type: String,
},
description: {
type: String,
}
original_poster: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true
},
tags: {
type: [String]
}
})
所以,例如:
app.get('/', (req,res) => {
Post.find({ original_poster: req.session.user }).then((posts) =>{
res.send(JSON.stringify(posts));
}) //where req.session.user is an id (the logged in user's object id or _id)
})
基本上在sql语法中,它可能类似于:
SELECT * FROM POSTS WHERE ORIGINAL_POSTER = <req.session.user>
req.session.user返回所有帖子的正确方法是什么?
答案 0 :(得分:1)
似乎original_poster
字段表示对用户模型的引用,如果req.session.user
存储为字符串,则必须将其强制转换为objectID
:
const mongoose = require('mongoose');
...
let userId = mongoose.Types.ObjectId(req.session.user);
Post.find({ original_poster: userId }).then((posts) => {
res.send(JSON.stringify(posts));
});