首页 > 解决方案 > 将 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 } }

我正在查看一个图书馆,因为写出所有内容可能非常乏味,并且在需要大量字段的情况下

标签: node.jsexpressmongooselodash

解决方案


您可以使用 lodash,但在创建新产品时将 body 作为键传递。你需要传播身体的钥匙。

const body = _.pick(req.body, ['produtTitle', 'productImg', 'productPrice', 'productDesc'])

    const product = new Product({
      ...body,
      userId: req.userId
    });

推荐阅读