【问题标题】:passing arrays in curl command to mongoDB将 curl 命令中的数组传递给 mongoDB
【发布时间】:2021-02-25 15:08:42
【问题描述】:

我为我的数据使用下面的 mongoDB 架构

const mongoose = require("mongoose");

const subSchema = require("../../src/models/Course");

const All_CoursesSchema = new mongoose.Schema({
    Student_name: {
      type: String,
      required: true
    },
    course_names: [ {grade: {type: String, required: true}, course_name: {type: String,required: true}}],
  });
  
  const All_Courses = mongoose.model('Courses', All_CoursesSchema)
  
  module.exports = All_Courses

我还使用 node.js 中的 express 进行了以下 api 调用

router.post('/add-courses', (req,res)=>{
  const course = new All_Courses(req.body);
  console.log(course);
  course.save()
      .then((result)=>{
        res.send(result)
      })
      .catch((err) =>{
        console.log(err);
      });
});

我尝试使用此 curl 请求传递参数,但它返回一个空数组,仅正确设置了 student_name

curl -X POST -d "Student_name=hadi" -a "course_name=[{grade=78&course_name=cmps}]" http://localhost:5000/api/add-courses

我如何使用 curl 发出正确的请求??会得到帮助

【问题讨论】:

  • 即使Student_name=hadi 也不是正确的javascript;文字“hadi”周围没有引号。 new All_Courses(req.body) 真的有用吗....?
  • 如果我在函数中硬编码我的值,All_courses() 可以工作。例如 All_courses(student_name="x", .....) 所以我猜如果我在 curl 中传递这些值,它应该可以正常工作。但我无法对其进行测试,因为我无法弄清楚在 curl 中传递它们的正确格式
  • 我很确定 req.body 只是将 POST 材料作为一个大字符串,而不是带有名称和类型的结构化参数。我认为正在发生的事情是student_name = "x" 被评估为All_courses(student_name),其中student_name 是单个字符串变量;简而言之,你打电话给All_courses("x")

标签: javascript node.js mongodb express curl


【解决方案1】:

我相信您正在混合使用文本和变量赋值以及 JSON 和 javascript。让我们后退一步,假设我们想用结构良好的 JSON 调用我们的 API。所以对curl 的调用变成了这样:

curl -g -X POST -d '{"student_name":"hadi","course_name":[{"grade":78,"course_name":"cmps"}]}' http://localhost:5000/api/add-courses

POST 的一个好处是您不必担心 URL 编码,因为 URL 中没有空格、引号等;它们在 POST 正文中是“安全的”。

这将作为 JSON 文本访问您的 express/node 服务器,您必须将其解析为一个对象以 dp 一些有趣的东西:

router.post('/add-courses', (req,res)=>{
  var obj = JSON.parse(req.body);
  const course = new All_Courses(obj);
  ...

【讨论】:

    猜你喜欢
    • 2016-06-25
    • 2018-01-27
    • 2018-03-14
    • 1970-01-01
    • 2021-09-21
    • 2019-12-19
    • 1970-01-01
    • 2017-01-30
    • 2021-11-25
    相关资源
    最近更新 更多