【问题标题】:NodeJS not passing object key-value pairs to MongoDB via PostmanNodeJS 没有通过 Postman 将对象键值对传递给 MongoDB
【发布时间】:2015-12-10 14:26:37
【问题描述】:

我是 MongoDB 的新手,并且已经感受到 [在 Windows 上] 使用它时所带来的挫败感。我的问题是我正在通过 POSTMAN 创建一个 USER 对象。

这是我的 server.js 代码,用于将用户发布到 MongoDB。
附言此外,Sublime 仅突出显示 .name,而不突出显示 .username 和 .password。

apiRouter.route('/users')

    // create a user (accessed at POST http://localhost:8080/users)
    .post(function(req, res) {

        var user = new User();      // create a new instance of the User model
        user.name = req.body.name;  // set the users name (comes from the request)
        user.username = req.body.username;  // set the users username (comes from the request)
        user.password = req.body.password;  // set the users password (comes from the request)

        user.save(function(err) {
            if (err) {
                // duplicate entry
                if (err.code == 11000) 
                    return res.json({ success: false, message: 'A user with that username already exists. '});
                else 
                    return res.send(err);
            }

            // return a message
            res.json({ message: 'User created!' });
        });

    })

也许我不知道一些警告。谢谢。

【问题讨论】:

  • 你从邮递员那里得到什么错误?
  • @inspired 无。它吐出成功消息 - 用户创建。从传递的参数中,仅添加 .username。
  • 对不起,您的错误是什么?如果您在保存之前console.log(req.body.username,req.body.password);,您会在控制台中获得正确的值吗?
  • @inspired 控制台显示正确的凭据。此外,尝试更新用户会显示他的用户名和密码。这是一个新的屏幕截图 - take.ms/sKCQV。但 JSON 响应不包括他的通行证。

标签: node.js mongodb postman


【解决方案1】:

确保您在请求参数解析后连接到您的 mongoDB 实例。

例如:

//parse request parameters

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

//connect to MongoDB

mongoose.connect('mongodb://localhost:27017');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-02
    • 2018-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多