【发布时间】:2020-11-14 02:45:38
【问题描述】:
我已经创建了帖子路线来将帖子存储在数据库中。这是一条受保护的路线,因此用户只有在输入登录详细信息后才能存储帖子。当我在邮递员中发帖时,我看到对象中没有返回用户电子邮件。即使在 mongodb 集合中,我也看不到与该帖子关联的电子邮件。如何在帖子对象中包含电子邮件。我不希望用户在发布时一次又一次地输入电子邮件,因为他们已经登录了。所以我有点想将电子邮件与帖子一起自动存储。希望我说得通。有人可以帮我解决这个问题吗?
现在对象有点像这样存储在 mongodb 的帖子集合中
_id: ObjectId("5f1a99d3ea3ac2afe5"),
text: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. ",
user:ObjectId("5f1a99d3eac2c82afe5"),
age:20,
country:"India",
gender:"male",
date:2020-07-24T08:23:35.349+00:00,
__v:0
我也想要上述对象中的电子邮件。
后模型
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const PostSchema = new Schema ({
user: {
type: Schema.Types.ObjectId,
ref: 'users'
},
text: {
type: String,
required: true
},
name: {
type: String
},
email: {
type: String
}
,
age: {
type: Number,
required: true
},
gender: {
type: String,
required: true
},
country: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
})
module.exports = Post = mongoose.model('post', PostSchema)
发布路线
const express = require('express');
const router = express.Router();
const auth = require('../../middleware/auth')
const { check, validationResult} = require('express-validator');
const User = require('../../models/User')
const Post = require('../../models/Post')
router.post('/', [auth, [
check('text', 'Text is required').not().isEmpty()
]], async (req,res)=>{
const errors = validationResult(req);
if(!errors.isEmpty()){
return res.status(400).json({errors: errors.array()})
}
try {
const user = await (await User.findById(req.user.id)).isSelected('-password')
const newPost = new Post({
text: req.body.text,
name: user.name,
user: req.user.id,
age: req.body.age,
country: req.body.country,
gender: req.body.gender,
email: req.user.email // this email is not stored with the post and I want this to be automatically posted in the collection without the user having to type it again to save the post
})
const post = await newPost.save();
res.json(post);
} catch (err) {
console.error(err.message);
res.status(500).send('Server Error')
}
})
module.exports = router;
用户模型
const mongoose = require('mongoose');
const UserSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
})
module.exports = User = mongoose.model('user', UserSchema);
【问题讨论】:
-
这不是您问题的答案,但电子邮件不是存储在您的
user文档中吗?如果是的话,你可以从那里抓住它。但我不确定是否有必要将电子邮件保存在两个不同的位置(post和user),因为您在post文档中引用了user.id。 -
实际上,在他们将文本发布到我的数据库后,我需要通过电子邮件将文档发回给他们,而查看哪个帖子属于哪个电子邮件将是一个巨大的痛苦,这就是我想要电子邮件的原因包括
-
能否请您也包括有问题的用户模型以便更好地理解?
-
你在 route ('/') 中传递的 body 是什么?您确定电子邮件已保存在用户的收藏夹中吗?
-
好的,所以现在不能在邮递员中检查,对吧?但我可以稍后在前端做到这一点?
标签: node.js mongodb express mongoose