Nodejs / Mongoose将变量传递给mongoose函数

时间:2016-04-07 21:48:01

标签: javascript node.js mongodb mongoose

我是Node.js和Mongoose的新手,需要一些帮助。所以我首先创建一个名为beerObjects的数组。然后我向breweryDB发出请求并在此数组中存储信息。

request(options, function (error, response, body) {
            if (error) throw new Error(error);
            obj = JSON.parse(body);
            data = obj['data'];
            for(i = 0; i < data.length; i++) {
                var newBeer = new Beer();
                newBeer.id = data[i]['id'];
                newBeer.name = data[i]['name'];
                newBeer.description = data[i]['description'];
                newBeer.abv = data[i]['abv'];
                if (data[i].hasOwnProperty('labels')) {
                    newBeer.image = data[i]['labels']['large'];
                }

                beerObjects.push(newBeer);
                console.log(beerObjects[i].name);
            }
            addBeersToDatabase(beerObjects);
        });

我有另一个函数来获取这个数组并将信息存储在我的mongo数据库中。

function addBeersToDatabase(beerObjects) {
console.log(beerObjects.length);
for (i = 0; i < beerObjects.length; i++) {
    console.log(beerObjects[i].id);
    // check if beer is already in database
    Beer.count({id: beerObjects[i].id}, function(err, count){
        if (err) {
            handleError(err);
        }
        if (count == 0) {
            // add new beer to database
            var newBeer = new Beer();
            newBeer.id = beerObjects[i].id;
            newBeer.name = beerObjects[i].name;
            newBeer.description = beerObjects[i].description;
            newBeer.abv = beerObjects[i].abv;
            newBeer.image = beerObjects[i].image;

            newBeer.save(function(err) {
                if (err) {
                    throw err;
                }
            });

        }
        else {
            // beer is already in database
        }
    });
}

}

在addBeerToDatabase()函数的开头,定义了beerObject,并且console.log()语句输出了正确的信息。但是在Mongoose函数Beer.count()中,我收到此错误消息。

newBeer.id = beerObjects[i].id;
TypeError: Cannot read property 'id' of undefined

这个'id'是beerObjects [i]的id,而不是newBeer。如何正确地将beerObjects传递给mongoose函数并在该函数中使用它?

编辑:

function addBeersToDatabase(beerObjects) {
for (i = 0; i < beerObjects.length; i++) {
    console.log(beerObjects[i].beerId);
    var currentBeer = beerObjects[i];

    // check if beer is already in database
    Beer.findOne({'beerId': currentBeer.beerId}, function(err, beer){
        if (err) {
            handleError(err);
        }
        if (beer) {
            // beer is already in database
        }
        else {
            // add new beer to database
            console.log(currentBeer.name);
            saveNewBeer(currentBeer);
        }
    });
}

}

function saveNewBeer(currentBeer) {
var newBeer = new Beer();
newBeer.beerId = currentBeer.beerId;
newBeer.name = currentBeer.name;
newBeer.description = currentBeer.description;
newBeer.abv = currentBeer.abv;
newBeer.image = currentBeer.image;

newBeer.save(function(err) {
    if (err) {
        throw err;
    }
});

}

这段代码只添加了啤酒对象中最后一项的n个重复项(其中n = beerObjects.length)。

2 个答案:

答案 0 :(得分:1)

编辑:

您正在使用beerObject[i].id循环并“抓取”啤酒,然后您异步检查计数,当您开始设置newBeer.id时,您处于不同的范围。对此的补救措施是将变量设置为beerObject[i].id并将其作为您在Beer.count中寻找的'啤酒'传递:

像这样:

for (i = 0; i < beerObjects.length; i++) {
    console.log(beerObjects[i].id);
    var checkBeer = beerObjects[i]
    // check if beer is already in database
    Beer.count({id: checkBeer.id}, function(err, count){
        if (err) {
            handleError(err);
        }
        if (count == 0) {
            // add new beer to database
            var newBeer = new Beer();
            newBeer.id = checkBeer.id;
... and so on

答案 1 :(得分:1)

MongoDB ID是自动生成的,因此除非您在mongoose模型中将_id定义为String,否则无法将任何值添加到_id属性中。

例如。

var mongoose = require('mongoose');
var beerSchema = new mongoose.Schema({
    _id: String,
    name: String,
    // rest of beer properties
});

module.exports = mongoose.model('Beer', beerSchema);

在你的功能中,

function addBeersToDatabase(beerObjects) {
    for (i = 0; i < beerObjects.length; i++) {
    Beer.findbyId(beerObjects[i].id, function(err, beers){
        if (beers.lenght == 0) {
            // add new beer to database
            var newBeer = new Beer();
            newBeer._id = beerObjects[i].id;
            newBeer.name = beerObjects[i].name;
            newBeer.description = beerObjects[i].description;
            newBeer.abv = beerObjects[i].abv;
            newBeer.image = beerObjects[i].image;
            newBeer.save();
        }
        else {
            // beer is already in database
        }
    });
}

如果您想使用默认的mongoId,只需要删除模型中的_id: String和函数中的newBeer._id = beerObjects[i]id即可。我希望这会对你有所帮助。