首页 \ 问答 \ 邮差发布请求中未插入猫鼬模型密钥(Mongoose model keys not being inserted in Postman post request)

邮差发布请求中未插入猫鼬模型密钥(Mongoose model keys not being inserted in Postman post request)

我试图使用下面的post方法来创建新文档。 但是当我在Postman中发送一个post请求(例如http:// localhost:3000 / api / posts?title = HeaderThree )时,会创建一个新文档,但是键和值都会丢失。

router.route('/posts')
    .get(function(req, res) {
        Post.find(function(err, posts) {
            if (err) { return res.send(err)}
            res.json(posts)
        })
    })
    .post(function(req, res) {
        const post = new Post(
            {
                title: req.body.title,
                text: req.body.text
            }
        );

        post.save(function(err, post) {
            if (err) { return res.send(err)};
            res.json({ message: 'Post added!'});
        });
    });

架构是这样的:

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const PostSchema = new Schema(
    {   
        date: {type: Date, default: Date.now},
        title: {type: String},
        text: {type: String },
        comments: {type: Array}
    }
)

module.exports = mongoose.model('PostSchema', PostSchema);

I'm trying to use the post method below to create new documents. But when I send a post request in Postman (e.g. http://localhost:3000/api/posts?title=HeaderThree) a new document is created but the keys and values are missing.

router.route('/posts')
    .get(function(req, res) {
        Post.find(function(err, posts) {
            if (err) { return res.send(err)}
            res.json(posts)
        })
    })
    .post(function(req, res) {
        const post = new Post(
            {
                title: req.body.title,
                text: req.body.text
            }
        );

        post.save(function(err, post) {
            if (err) { return res.send(err)};
            res.json({ message: 'Post added!'});
        });
    });

The schema is this:

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const PostSchema = new Schema(
    {   
        date: {type: Date, default: Date.now},
        title: {type: String},
        text: {type: String },
        comments: {type: Array}
    }
)

module.exports = mongoose.model('PostSchema', PostSchema);

原文:https://stackoverflow.com/questions/48672846
更新时间:2023-12-10 20:12

最满意答案

你需要循环结果:

....
if(mysqli_num_rows($result) > 0) {
    while($row = mysqli_fetch_assoc($result)) { //<-----
        $PART_NUMBER = $row["PART_NUMBER"];
        $FSC = $row["FSC"];
        $NIIN = $row["NIIN"];
        $ITEM_NAME = $row["ITEM_NAME"];

        echo $ITEM_NAME, ", " .$PART_NUMBER, ", " .$FSC, ", " .$NIIN;
    }
} else {
...

你应该使用准备好的语句,看看如何在这里: 我如何防止PHP中的SQL注入?


You need to loop the results:

....
if(mysqli_num_rows($result) > 0) {
    while($row = mysqli_fetch_assoc($result)) { //<-----
        $PART_NUMBER = $row["PART_NUMBER"];
        $FSC = $row["FSC"];
        $NIIN = $row["NIIN"];
        $ITEM_NAME = $row["ITEM_NAME"];

        echo $ITEM_NAME, ", " .$PART_NUMBER, ", " .$FSC, ", " .$NIIN;
    }
} else {
...

And you should use prepared statements, take a look how to here: How can I prevent SQL injection in PHP?

相关问答

更多
  • 您可以在同一SQL查询中执行嵌套查询并将PHP保留在其中: 'SELECT * FROM (SELECT * FROM foo WHERE bar="something") AS q1 WHERE q1.bar2 = "something else"' You could do a nested query in the same SQL query and keep PHP out of it: 'SELECT * FROM (SELECT * FROM foo WHERE bar="something ...
  • 你需要循环结果: .... if(mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { //<----- $PART_NUMBER = $row["PART_NUMBER"]; $FSC = $row["FSC"]; $NIIN = $row["NIIN"]; $ITEM_NAME = $row["ITEM_NAME"]; ...
  • 我建议使用相同的页面显示结果,过滤器是否适用于位置或卧室数量。 您总是可以在SQL中使用WHERE (1 = 1) ,以便可以附加AND (Location='$loc')或AND (Beds='$bed') ,尽管最好使用参数。 完成设置后,您可以修改链接。 假设您的目标网页是webproperty.php 。 将该URL存储在变量$urlDest 。 当您按位置生成链接以进行过滤时,将$_GET中不是loc任何变量添加到$urlDest ,得到类似webproperty.php?bed=2 。 在迭代您 ...
  • MySQL可以处理多个插入语句。 Barmar强调一些连接管理器不处理该构造。 假设SQL发送不变,在$ data的赋值中似乎缺少逗号。 $ data = $ _GET ['data']. "(-1, -1)"; 应该... $data = $ _GET['data'] . ", (-1, -1)"; 当且仅当值$ _GET ['data']不为空时,例如data =“(ID,DISTANCE),(ID,DISTANCE)”。 MySQL can handle multiple insert state ...
  • 触发return ,函数结束,并且不执行任何其他代码行。 如果要延迟数据的返回直到函数的后期,则创建变量,赋值,并在准备好后返回变量。 例如,您可以调整代码以为$data创建数组,如下所示: function dbGet($conn, $table, $select, $where, $cond) { $data = array(); ... while ( $row = $result->fetch_assoc() ) { $data[] = $row; } ...
  • regionI希望你转发你的查询条目:) 我要做的是使用子查询压缩查询 SELECT * FROM registrar_claims WHERE reg_region IN (SELECT region FROM regions WHERE staff_100_id='$id') AND ready_to_process='yes' ORDER BY claim_id ASC 这应该产生所需的有序结果 regionI hope you are escaping your query entri ...
  • 我一直在研究同一主题(搜索关键字)一段时间,这是我做到的: $words = $_POST['keywords']; if(empty($words)){ //redirect somewhere else! } $parts = explode(" ",trim($words)); $clauses=array(); foreach ($parts as $part){ //function_description in my case , replace it with whateve ...
  • 我想MDB2可能会以某种方式改变你的查询。 所以要找到它你需要记录在你的数据库中执行的查询(请参阅 : http : //dev.mysql.com/doc/refman/5.1/en/query-log.html以及如何显示最后在MySQL上执行的查询? )。 ...ok I found out what was the problem: I cannot execute multiple sentences in one go. I had to split them into single sente ...
  • 你正在寻找一个名为'action AND Genre like Adventure'的流派,你应该做些什么 SELECT * FROM animelist WHERE Genre like 'action' OR Genre like 'Adventure' ORDER BY NAME DESC 多数民众赞成你的问题,但你应该使用预备语句来防止SQL注入,并尽可能使用=而不是像。 Okey I solved it by using FIND_IN_SET

相关文章

更多

最新问答

更多
  • Runnable上的NetworkOnMainThreadException(NetworkOnMainThreadException on Runnable)
  • C ++ 11 + SDL2 + Windows:多线程程序在任何输入事件后挂起(C++11 + SDL2 + Windows: Multithreaded program hangs after any input event)
  • AccessViolationException未处理[VB.Net] [Emgucv](AccessViolationException was unhandled [VB.Net] [Emgucv])
  • 计算时间和日期差异(Calculating Time and Date difference)
  • 以编程方式标签NSMutableAttributedString swift 4(Label NSMutableAttributedString programmatically swift 4)
  • C#对象和代码示例(C# objects and code examples)
  • 在python中是否有数学nCr函数?(Is there a math nCr function in python? [duplicate])
  • 检索R中列的最大值和第二个最大值的行名(Retrieve row names of maximum and second maximum values of a column in R)
  • 给定md5哈希时如何查找特定文件(How to find specific file when given md5 Hash)
  • Python字典因某些原因引发KeyError(Python Dictionary Throwing KeyError for Some Reason)
  • 如何让Joomla停止打开新标签中的每个链接?(How do I get Joomla to stop opening every link in a new tab?)
  • DNS服务器上的NS记录不匹配(Mismatched NS records at DNS server)
  • Python屏幕捕获错误(Python screen capture error)
  • 如何在帧集上放置div叠加?(How to put a div overlay over framesets?)
  • 页面刷新后是否可以保留表单(html)内容数据?(Is it possible to retain the form(html) content data after page refreshed?)
  • 使用iTeardownMyAppFrame和iStartMyAppInAFrame在OPA5测试中重新启动应用程序超时(Restart app within OPA5 test using iTeardownMyAppFrame and iStartMyAppInAFrame timed out)
  • 自动拆分文本内容到列(Automatically splitting text content into even columns)
  • 在r中的循环中将模型名称分配给gbm.step(assigning model names to gbm.step in loop in r)
  • 昆明哪里有电脑等级考试二级C培训?
  • C ++模板实例化,究竟是什么意思?(C++ template instantiation, what exactly does it mean?)
  • 帮助渲染来自fields_for的部分内容(Help to render a partial from fields_for)
  • 将url.action作为json对象返回mvc(return url.action as json object mvc)
  • 使用.BAT中的.application文件类型运行ac#Console App(Run a c# Console App with .application file type from a .BAT)
  • 将bindingRedirect添加到.Net标准库(Adding a bindingRedirect to a .Net Standard library)
  • Laravel版本升级会影响您的控制器吗?(Laravel version upgrade affects your controller?)
  • imaplib.error:命令SEARCH在状态AUTH中非法,只允许在SELECTED状态(imaplib.error: command SEARCH illegal in state AUTH, only allowed in states SELECTED)
  • 如何在eclipse debug impala前端
  • 如何通过Ajax API处理多个请求?(How to handle multiple requests through an Ajax API? [closed])
  • 使用Datetime索引来分析数据框数据(Using Datetime indexing to analyse dataframe data)
  • JS 实现一个菜单效果