node.js - 将 userId 添加到 post 请求节点 express
问题描述
我有一个节点应用程序,当我创建一个帖子时,我必须传递创建帖子 ID 的人以及帖子。问题是我一直都是这样写的
const imageUrl = req.file.path;
const title = req.body.title;
const content = req.body.content;
const post = new Post({
title: title,
content: content,
imageUrl: imageUrl,
creator: req.userId
});
我现在的问题是,如果我有很多这些,是否不可能使用像 lodash 这样的库来挑选所有领域,比如
const body = _.pick(req.body, ['produtTitle', 'productImg', 'productPrice', 'productDesc'])
console.log(`THIS IS ${body}`)
const product = new Product({
body,
userId: req.userId
});
每次我这样尝试时,我都会得到 404 并且在我的终端中我得到
消息:'路径
productPrice
是必需的。',名称:'ValidatorError',属性:[Object],种类:'required',路径:'productPrice',值:未定义,原因:未定义,'$isValidatorError':true },
对于所有领域
如果我这样做const product = new Product(req.body)
,我只会收到一个 404 错误
message: 'Path `userId` is required.',
name: 'ValidatorError',
properties: [Object],
kind: 'required',
path: 'userId',
value: undefined,
reason: undefined,
'$isValidatorError': true } }
我正在查看一个图书馆,因为写出所有内容可能非常乏味,并且在需要大量字段的情况下
解决方案
您可以使用 lodash,但在创建新产品时将 body 作为键传递。你需要传播身体的钥匙。
const body = _.pick(req.body, ['produtTitle', 'productImg', 'productPrice', 'productDesc'])
const product = new Product({
...body,
userId: req.userId
});
推荐阅读
- r - R脚本RDCOMClient无法打开xlsx文件
- r - 如何在ggplot2中指向一个历史?
- ios - 核心运动更新
- android - Android切换到多种布局
- vuejs3 - Vue 反应性:使用提供和注入创建反应性数据
- c++ - curl.lib 缺失(Visual Studio 2019,C++)
- php - 从注册到 Woocommerce Checkout 获取自定义字段
- python - Pandas:如何根据频率有效过滤数据
- mysql - 显示创建用户'root'@'localhost';给我错误 1064 (42000):您的 SQL 语法有错误;
- java - 为什么套接字 connect() 方法超时?netcat (nc) 工作正常