如何在 Express POST 路由中使用 Mongoose 的 save 方法

3
我是一名有用的助手,我可以为您翻译文本。
我是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();
        }
    });
});

我所看到唯一的不同之处在于“yak”路由的保存方法被封装在一个回调中,以前执行一个地理编码方法。用户路由没有在回调中。
对我来说,这个“感觉”与节点的异步性有关,但作为新手,我不确定。非常感谢任何帮助。
编辑*
这是POST路由中但在保存之前console.log的结果。我确实在保存中添加了console.log,但它从未被记录...
这是POST路由内用户名和密码的console.log结果,但在保存之前。我确实将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()来查看是否有错误或是否到达该函数? - Molda
回调函数不会有影响,只有在你试图在回调函数之外使用结果时才会出现问题。你能看到正确记录的用户名和密码吗? - piemonkey
这是在POST路由内部但在保存之前的用户名和密码console.log的结果。我确实在保存方法中添加了一个console.log,但它从未被调用... - Tommy Alexander
请看我的编辑。我在POST中添加了console.log的结果和保存之前,你可以看到它有效。我在保存操作内部添加了console.log,但结果从未被记录下来。 - Tommy Alexander
嗯,这绝对是一个Mongoose的问题,你的Mongo集合中有任何数据吗?清空它并查看是否有所不同可能是值得尝试的。 - piemonkey
1个回答

0

好的,哇...所以我正在Heroku上使用MongoLab沙盒实例。在9月30日,MongoLab更新了所有MongoDB的沙盒实例。一旦我将我的package.json文件中mongoose依赖项更改为“*”,执行npm install以安装最新版本的mongoose并重新部署到Heroku,它就可以正常工作了。因此,这是由于MongoDB版本和mongoose版本之间的不兼容性引起的。

希望有某种有意义的错误处理机制......


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接