如何从数据库获取数据&如果数据不可用,则输入存储在nodejs数据库中的数据

时间:2017-05-16 08:58:09

标签: javascript node.js

如何从数据库获取数据&如果数据不可用,则输入存储在nodejs中的数据库中的数据。

我有一个代码:

router.get('/pincode/:pincode', function (req, res) {
    Pincode.find({
        pincode: req.params.pincode
    }, function (err, pincodes) {
        if (pincodes == '') {
            var pincodeData = new Pincode({
                pincode: req.params.pincode,
                country: req.body.country,
                state: req.body.state,
                district: req.body.district,
                taluka: req.body.taluka,
                city: req.body.city,
                area: req.body.area

            });
            pincodeData.save(function (err, results) {
                if (err) {
                    return err;
                } else {

                    console.log("Got a response: ", results);
                    // console.log("data:"+body);
                }
            });

        }
        res.json(pincodes);
    });
});

1 个答案:

答案 0 :(得分:0)

Pincode.find - return an array so if(pincodes == '') - incorrect. You can use if(!pincodes.length) or use Pincode.findOne() and if(pincode), for example:

router.get('/pincode/:pincode', function (req, res) {
    Pincode.findOne({
        pincode: req.params.pincode
    }, function (err, pincode) {
        if (!pincode) {
            var pincodeData = new Pincode({
                pincode: req.params.pincode,
                country: req.body.country,
                state: req.body.state,
                district: req.body.district,
                taluka: req.body.taluka,
                city: req.body.city,
                area: req.body.area

            });
            pincodeData.save(function (err, results) {
                if (err) {
                    return err;
                } else {

                    console.log("Got a response: ", results);
                    // console.log("data:"+body);
                }
            });

        }
        res.json(pincode);
    });
});