【问题标题】:How to use Mongoose save method in Express POST route如何在 Express POST 路由中使用 Mongoose 保存方法
【发布时间】:2016-01-02 15:44:59
【问题描述】:

我是 Express 和 Node 的新手,有一个我不明白的问题。我已经定义了两个不同的 Express 路由来对两个不同的 Mongoose 数据模型进行 POST 请求。一个工作正常并正常返回,另一个在 Heroku 日志中返回状态 204 然后超时,就像保存甚至没有执行一样......

这里是“Yak”模型和关联的 POST 路由,它保存对象并将预期结果返回给我的 Angular 客户端:

模型定义:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var YakSchema   = new Schema({
catagory: String,
loc: {
    type: [Number],  // [<longitude>, <latitude>]
    index: '2d'      // create the geospatial index
},
yakName:String,
yakDescription:String,
yakPhone:String,
yakOwner:String
});

module.exports = mongoose.model('Yak', YakSchema);

还有 POST 路线

router.route('/yaks')

.post(function(req, res) {
    var yak = new Yak();

    //First, need to get lat, lng from the address
    var addressString = req.body.city + ", " + req.body.street + ", " + req.body.state + ", " + req.body.postalcode;
    geocoder.geocode(addressString, function (err, data) {

        //error handling needed
        if (err){
            res.status(500).json({
                status:500,
                error:err
            });
            res.end();
        }

        var coord = data['results'][0]['geometry']['location'];
        var lat = coord.lat;
        var lng = coord.lng;

        //Second, use the Model to save the yak with a geoJSON point

        yak.catagory = req.body.catagory;
        yak.loc = [lng, lat];
        yak.yakName = req.body.yakName;
        yak.yakDescription = req.body.yakDescription;
        yak.yakPhone = req.body.yakPhone;
        yak.yakOwner = req.body.yakOwner;
        yak.save(function (err) {
            if (err) {
                res.status(500);
                res.json({
                    status: 500,
                    error: err
                });
                res.end();
            }
            else {
                res.json({
                    status: 200,
                    yak: yak
                });
                res.end();
            }
        });
    });
});

这是不起作用的用户模型和用户路由

var mongoose = require('mongoose');
var Schema = mongoose.Schema;


var UserSchema = new Schema({
username: { type: String, required: true, index: { unique: true } },
password: { type: String, required: true }
});

module.exports = mongoose.model('User', UserSchema);

还有 POST 路线

   router.route('/users')
    .post(function(req, res) {


    console.log(req.body.username);
    console.log(req.body.password);


    var user = new User();
    user.username = req.body.username;
    user.password = req.body.password;

    console.log(user);

    user.save(function(err){

        if (err) {
            res.status(500);
            res.json({
                status: 500,
                error: err
            });
            res.end();
        }
        else {
            res.json({
                status: 200,
                user: user
            });
            res.end();
        }
    });
});

我看到的唯一区别是“牦牛”路线的保存方法被包装在一个回调中,用于对位置进行地理编码的先前执行的方法。用户路由不在回调中。

这对我来说“感觉”与节点的异步性质有关,但我不确定。非常感谢任何帮助

编辑*

这是 POST 路由中控制台 .log 的结果,但在保存之前。我确实在保存中添加了一个 console.log,但它永远不会被注销......

这是用户名和密码的 console.log 的结果,在 POST 路由内部但在保存之前。我确实在 save 方法中添加了一个 console.log,但它从未被调用....

heroku[router]: at=info method=OPTIONS     path="/api/users" host=frozen-       
peak-5921.herokuapp.com request_id=6230237d-7adc-4a51-8a26-03da99f8b7e3    
fwd="74.202.146.157" dyno=web.1 connect=2ms service=14ms status=204 bytes=289
 app[web.1]: asd
 app[web.1]: me@mail.com
 app[web.1]: { password: 'asd',
 app[web.1]:   username: 'me@mail.com',
 app[web.1]:   _id: 5612e098a7f49c1100000001 }
 heroku[router]: at=error code=H12 desc="Request timeout" method=POST 
path="/api/users" host=frozen-peak-5921.herokuapp.com request_id=f6c0fde8-   
c2e4-49e5-ad65-ba6afed3b731 fwd="74.202.146.157" dyno=web.1 connect=1ms 
service=30001ms status=503 byte

【问题讨论】:

  • 你不需要使用 res.end() 因为 res.json() 在内部调用 res.end() 。你可以在你的 user.save 函数中添加一些 console.log() 来查看是否有任何错误,或者它是否到达那里
  • 回调不会产生影响,只有当您尝试在回调之外使用结果时才会出现问题。您看到正确记录的用户名和密码了吗?
  • 这里是用户名和密码的console.log结果在POST路由内部但在保存之前。我确实在 save 方法中添加了一个 console.log,但它从未被调用....
  • 查看我的编辑。我在 POST 中添加了 console.log 的结果,在保存之前,您可以看到它有效。我在保存中添加了一个console.log,结果永远不会被记录..
  • 嗯,这听起来像是 Mongoose 的问题,你的 Mongo 集合中有数据吗?可能值得清除它,看看这是否会有所作为。

标签: node.js rest express mongoose


【解决方案1】:

好的,哇....所以我在 Heroku 上使用 MongoLab 沙箱实例。 9 月 30 日,MongoLab 更新了他们所有的 MongoDB 沙箱实例。一旦我将 package.json 文件 mongoose 依赖项更改为“*”,执行 npm install 以安装最新版本的 mongoose 并重新部署到 Heroku,一切正常。所以这是由于 MongoDB 版本和 mongoose 版本不兼容造成的。

对此效果进行某种有意义的错误处理会很好......

【讨论】:

    猜你喜欢
    • 2018-10-25
    • 2018-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-08
    • 2019-03-18
    相关资源
    最近更新 更多