即使我检查文档是否已存在,Mongoose仍在保存文档

时间:2018-04-03 21:14:50

标签: javascript mongodb mongoose

我在保存作者之前尝试检查作者是否在mongo中。当我通过创建作者函数运行我的第一个rss文档时,所有作者都保存在数据库中 - 即使他们在feed中编写了两个项目。

奇怪的是,如果我再次运行feed,mongoose似乎意识到作者已经存在并且不再添加它们。有人可以向我解释发生了什么事吗?

function insertFeedItems(feedItems, newFeedID, callback) {
    feedItems.forEach((item) => {
        let firstName = item.author.substr(0, item.author.indexOf(' '));
        let lastName = item.author.substr(item.author.indexOf(' ') + 1);
        authorController.createAuthorInternally(firstName, lastName, function(author) {
            let aid = author.id;
            categoryController.createCategoryInternally(item.categories, function(categories) {
                // console.log('author: '+aid);
                // console.log('categories: '+categories);
            });
        });
    });

}


exports.createAuthorInternally = (firstName, lastName, callback) => {

    let author = authorFilter.validateAuthor(firstName, lastName);

    let queryParams = {
        $and: [{firstName: {$regex: firstName, $options: 'i'}},
            {lastName: {$regex: lastName, $options: 'i'}}],
    };

    let query = Author.findOne(queryParams).sort([['lastName', 'ascending']]);
    let findAuthor = query.exec();

    findAuthor.then((foundAuthor)=> {
        if (foundAuthor === null) {
            f1();
        }
    });

    function saveGuy() {
        return new Promise((resolve) => {
            let insertNewAuthor = author.save();
            resolve(insertNewAuthor);
        });
    }

    async function f1() {
        var name = await saveGuy();
    }
};

编辑:我尝试过不同的方式:

 Author.count(({'firstName': firstName}, { 'lastName': lastName }), function (err,count) {
        console.log(firstName + " " + lastName + " " + count);
                if(count === 0){
                    f1();
                }
    });

function saveGuy() {
    return new Promise((resolve) => {
        let insertNewAuthor = author.save();
        resolve(insertNewAuthor);
    });
}

async function f1() {
    var name = await saveGuy();
}

在这个新方法的第一次运行中,输出为:

Jon Brodkin 0
Peter Bright 0
Timothy B. Lee 0
Samuel Axon 0
Kyle Orland 0
Jon Brodkin 0
Kyle Orland 0
Megan Geuss 0
Cyrus Farivar 0
Peter Bright 0
Jim Resnick 0
Cyrus Farivar 0
Kyle Orland 0
Beth Mole 0
Ars Staff 0
Megan Geuss 0
Cyrus Farivar 0
John Timmer 0
Kyle Orland 0
Samuel Axon 0

在第二次运行时使用相同的RSS Feed:

Cyrus Farivar 3
Jon Brodkin 2
Kyle Orland 4
Megan Geuss 2
Jon Brodkin 2
Ars Staff 1
Peter Bright 2
Jim Resnick 1
Peter Bright 2
Kyle Orland 4
Megan Geuss 2
Cyrus Farivar 3
Timothy B. Lee 1
Samuel Axon 2
Kyle Orland 4
Beth Mole 1
Cyrus Farivar 3
John Timmer 1
Kyle Orland 4
Samuel Axon 2

在提供赏金时,这是我用来查找和保存的方法:

exports.createAuthorInternally = (firstName, lastName, callback) => {

   let query = Author.findOne({firstName: firstName,lastName: lastName});

    query.exec(function(err,doc) {
        if(err){console.log(err)}
        if(!doc){
            let auth = new Author({firstName: firstName, lastName: lastName});
            auth.save(auth, function(err,newdoc) {
                if(err){console.log(err)}
                callback(newdoc);
            });
        }else{
            callback(doc);
        }

    });

结果与以前的方法相同。

编辑: JohnnyHK指出了我的错误。我调整了代码以反映他的答案:

function insertFeedItems(feedItems,newFeedID){

    async.eachSeries(feedItems, function(item, eachCallBack) {

        let firstName = item.author.substr(0, item.author.indexOf(' '));
        let lastName = item.author.substr(item.author.indexOf(' ') + 1);
        async.waterfall([
                (callback) => {
                    authorController.createAuthorInternally(firstName, lastName, function(author) {
                        return callback(null, author, item.categories);
                    });
                },
                (author, categories, callback) => {
                    categoryController.createCategoryInternally(categories, function(categories) {
                        return callback(null, author, categories);
                    });
                },
                (author, categories, callback) => {
                    feedEntryController.createFeedEntry(item, author, categories, function(entry) {
                        return callback(null, author, categories, entry);
                    });
                },
            ],
            function(waterfallError) {
                if(!waterfallError){
                    eachCallBack();
                }
            });
    }, function(eachSeriesErr) {
        if(eachSeriesErr) {
            console.log('An item failed to process');
        } else {
            console.log('All items have been processed successfully');
        }
    });
}

1 个答案:

答案 0 :(得分:2)

JohnnyHK指出了我的错误。使用库,Async - 我调整了代码以反映他的答案:

function insertFeedItems(feedItems,newFeedID){

async.eachSeries(feedItems, function(item, eachCallBack) {

    let firstName = item.author.substr(0, item.author.indexOf(' '));
    let lastName = item.author.substr(item.author.indexOf(' ') + 1);
    async.waterfall([
            (callback) => {
                authorController.createAuthorInternally(firstName, lastName, function(author) {
                    return callback(null, author, item.categories);
                });
            },
            (author, categories, callback) => {
                categoryController.createCategoryInternally(categories, function(categories) {
                    return callback(null, author, categories);
                });
            },
            (author, categories, callback) => {
                feedEntryController.createFeedEntry(item, author, categories, function(entry) {
                    return callback(null, author, categories, entry);
                });
            },
        ],
        function(waterfallError) {
            if(!waterfallError){
                eachCallBack();
            }
        });
}, function(eachSeriesErr) {
    if(eachSeriesErr) {
        console.log('An item failed to process');
    } else {
        console.log('All items have been processed successfully');
    }
});
}