mongoose将数据写入数组对象

时间:2015-10-27 11:00:26

标签: node.js mongoose

我有一个模式将location定义为一个数组,我想在其中编写2个字符串(gmaps geocoding lat,long)。到目前为止,我无法让它工作,也无法弄清楚原因。任何帮助表示赞赏。

我的架构:

var mongoose = require('mongoose');
var uniqueValidator = require('mongoose-unique-validator');
var Schema = mongoose.Schema;

//shop schema
var ShopSchema = new Schema({
    name: { type: String, required: true, unique: true },
    address: { type: String, required: true },
    location: [{
        latitude: String,
        longitude: String
    }]
});

ShopSchema.plugin(uniqueValidator);

module.exports = mongoose.model('Shop', ShopSchema);

发布请求:

.post(function(req, res) {
            //create a shop
            var shop = new Shop();
            //set the shop information
            shop.name = req.body.name;
            shop.address = req.body.address;

            //get lat and long before saving from gmaps API
            //build gmaps API URL
            var urlAddress = req.body.address.replace(/ /gi, '+');
            var urlAPIKey = '&key=AIzaSyChkPdCaAaVZwYof8ZbKspokuYt41NlJ_0';
            var url = 'https://maps.googleapis.com/maps/api/geocode/json?address=';
            url = url.concat(urlAddress).concat(urlAPIKey);

            //make a request
            request({
                uri: url,
                method:"GET",
                timeout: 1000
                }, function(error, response, body) {
                    var gmaps = JSON.parse(body);
                    //display the geometry array
                    shop.location.latitude = gmaps.results[0].geometry.location.lat;
                    shop.location.longitude = gmaps.results[0].geometry.location.lng;
                    //save shop and check for errors
                    shop.save(function(err) {
                        if(err) {
                                return res.send(err);
                        }
                        else {
                            res.json({ message:'Shop created! '});
                        }
                    });
            });
        }) //closes .post on /shops

基本上我构建一个URL,发出一个返回JSON数据的请求,解析它,找到它,然后尝试编写它。当我尝试不使用对象(作为商店中的属性)编写它时,它起作用了。

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

在Shop架构中,location字段的类型为Array。在获得响应后,您必须将位置对象推送到数组中,但是您尝试创建一个对象而不是将对象推送到数组中。

更改代码的这两行
shop.location.latitude = gmaps.results[0].geometry.location.lat;
shop.location.longitude = gmaps.results[0].geometry.location.lng;

shop.location.push({ latitude: gmaps.results[0].geometry.location.lat.toString(), longitude: gmaps.results[0].geometry.location.lng.toString() });