【问题标题】:mongo input name saved as a Stringmongo 输入名称保存为字符串
【发布时间】:2021-04-13 22:04:40
【问题描述】:

当我使用 console.log(req.body) 时。它说

{
  'hero[title]': 'Lorem ipsum <br> Dolor sit amet.',
  'hero[description]': 'Dolor sit amet',
   uploadon: 'blahblah'
}

但它应该看起来像:

{
  hero[title]: 'Lorem ipsum <br> Dolor sit amet.',
  hero[description]: 'Dolor sit amet',
  uploadon: 'blahblah'
}

你知道问题所在吗? 我的 HTML 看起来像:

<div class="field">
    <label for="hero[title]">Titel</label>
    <input name="hero[title]" type="text">
</div>

<div class="field">
    <label for="hero[description]">Beschreibung</label>
    <textarea name="hero[description]" id="" cols="20" rows="5"></textarea>
</div>

更新:

我的猫鼬模型是:

var mongoose = require('mongoose');

var heroSchema = new mongoose.Schema({
    title: String,
    description: String,
    image: String
});

module.exports = mongoose.model("Hero", heroSchema);

这是我的路线:

app.post("/dashboard/hero", function(req, res) {
    Hero.create(req.body, function(err, newlyAdded){
        if(err){
            console.log(err);
        } else {
            console.log(newlyAdded);
            res.redirect("/dashboard/hero");
        }
    });
});

我想把它嵌入到一个 ejs 文件中。

【问题讨论】:

    标签: html node.js mongodb mongoose


    【解决方案1】:

    hero[title] 将尝试访问存储在title 中的变量,并在hero 对象中查找具有其值的属性——这将被破坏。这就是为什么当您的请求正文被解析为 JS 对象时,它被正确地表示为像 'hero[title]' 这样的字符串。

    【讨论】:

    • 好的,谢谢。但它应该显示在 req.body.hero 而不是 req.body
    • 你是做普通的表单提交还是AJAX?
    • 一个普通的 html 表单 - 检查我的更新以获取更多信息,也许它会有所帮助:)
    • 表单数据不支持嵌套对象,如果您需要使用 AJAX 发送 JSON 格式
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-05
    • 2014-05-07
    • 2023-04-08
    • 2020-02-11
    • 1970-01-01
    相关资源
    最近更新 更多