将文本和类别值传递给数据库(节点、反应、mongodb)
Posted
技术标签:
【中文标题】将文本和类别值传递给数据库(节点、反应、mongodb)【英文标题】:Pass text and categorie value to database (node,react,mongodb) 【发布时间】:2021-08-02 19:20:23 【问题描述】:大家好,我是新手,节点,我希望在创建帖子时传递文本和类别值(架构中的 catg)。
我能够传递文本并创建帖子,但我还想在创建帖子时添加一个类别
这是创建帖子的路径
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 User.findById(req.user.id).select('-password'); //don't want to send password back
const newPost = new Post(
text: req.body.text,
name: user.name,
avatar: user.avatar,
user: req.user.id,
//catg:req.
)
const post = await newPost.save();
res.json(post);
catch (err)
console.log(err.message);
res.status(500).send('Server Error');
);
这是添加帖子的操作
export const addPost = formData => async dispatch =>
const config =
headers:
'Content-Type': 'application/json'
;
try
const res = await axios.post('/api/posts', formData, config);
dispatch(
type: ADD_POST,
payload: res.data
);
dispatch(setAlert('Post Created', 'success'));
catch (err)
dispatch(
type: POST_ERROR,
payload: msg: err.response.statusText, status: err.response.status
);
;
这是帖子架构:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// Create Schema
const PostSchema = new Schema(
user:
type: Schema.Types.ObjectId,
ref: 'users'
,
text:
type: String,
required: true
,
name:
type: String
,
avatar:
type: String
,
isApproved:
type: Boolean,
default: false
,
catg:
type: String,
default: '0'
,
likes: [
user:
type: Schema.Types.ObjectId,
ref: 'users'
],
comments: [
user:
type: Schema.Types.ObjectId,
ref: 'users'
,
text:
type: String,
required: true
,
name:
type: String
,
avatar:
type: String
,
date:
type: Date,
default: Date.now
],
date:
type: Date,
default: Date.now
);
module.exports = Post = mongoose.model('post', PostSchema);
【问题讨论】:
【参考方案1】:大家好,这很简单,我只需在创建帖子时添加类别的值,它就可以工作
onSubmit=e =>
e.preventDefault();
addPost( text,value );
setText('');
谢谢大家
【讨论】:
以上是关于将文本和类别值传递给数据库(节点、反应、mongodb)的主要内容,如果未能解决你的问题,请参考以下文章