使用Node.js在MongoDB中插入深层文档

时间:2016-10-19 05:06:04

标签: node.js mongodb

我试图将一个城市插入国家/地区阵列内的状态数组中,这对我来说有点混乱。我使用MEAN。这是MongoDB模型:

var countrySchema = {
    countryName: { type: String, required: true },
    loc: [{ type: Number, required: true }],
    states: [{
        stateName: { type: String, required: true },
        loc: [{ type: Number, required: true }],
        cities: [{
            cityName: { type: String, required: true },
            loc: [{type: Number, required: true}]
        }]
    }]
};

当我插入新城市时,我需要更新cities内部states并推送另一个。

我正在使用POST metod,这看起来像这样:

api.post('/city/', wagner.invoke(function (Location) {
    return function (req, res) {
        return require('./Controllers/locationController').newCity(req, res, Location);
    };
}));

这是newCity函数:

module.exports.newCity = function (req, res, Location) {
    try {
        var locations = req.body.locations;
    } catch (error) {
        return res.status(status.BAD_REQUEST).json({error: error.toString()});
    }
    Location.update({"countryName": locations.countryName, "states.stateName": locations.states.stateName}, {'$push': {'cities': locations.states.cities}}, function (error, city) {
        if (error) {
            return res.status(status.INTERNAL_SERVER_ERROR).json({error: error.toString()});
        }
        if (!city) {
            return res.status(status.NOT_FOUND).json({error: error.toString()});
        }
        res.json({city: city})
    });
};

很可能是对更新功能的查询存在误解。

我发送以下JSON作为请求:

{
    "locations": {
        "countryName": "Mexico",
        "loc": [1, 2],
        "states": {
            "stateName": "test one",
            "loc": [1, 2],
            "cities": {
                "cityName": "City for test one",
                "loc": [1, 2]
            }
        }
    }
}

我收到了这个回复:

{
    "city": {
        "ok": 0
        "n": 0
        "nModified": 0
    }
}

1 个答案:

答案 0 :(得分:0)

我用projection operator解决了我的问题,我不知道,但我研究过。

解决方案看起来像这样:

module.exports.newCity = function (req, res, Location) {
    try {
        var locations = req.body.locations;
    } catch (error) {
        return res.status(status.BAD_REQUEST).json({error: error.toString()});
    }
    Location.update({
        "countryName": locations.countryName,
        'states.stateName': locations.states.stateName
    }, {
        '$push': {
            'states.$.cities': locations.states.cities
        }
    }, function (error, city) {
        if (error) {
            return res.status(status.INTERNAL_SERVER_ERROR).json({error: error.toString()});
        }
        if (!city) {
            return res.status(status.NOT_FOUND).json({error: error.toString()});
        }
        res.json({city: city});
    });
};