即使我检查文档是否已存在,Mongoose仍在保存文档 [英] Mongoose is saving documents even if I check to see if the document already exists

查看:62
本文介绍了即使我检查文档是否已存在,Mongoose仍在保存文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I cam trying to check to see if an author is in mongo before I save the author. When I run my first rss document through the create author function, all of the authors are saved in the DB - even if they have authored two items in the feed.

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

What's strange is that if I run the feed through again, mongoose seems to be aware that the authors already exists and does not add them again. Can someone please explain to me what is happening?

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();
    }
};

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

I've tried this a different way:

 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();
}

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

On the first run of this new method the output is:

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:

On the second run with the same 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

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

As of offering the bounty, this is the method that I'm using to find and save:

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);
        }

    });

结果与之前的方法相同。

The results are the same as in the previous methods.

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

JohnnyHK pointed out my error. I've adjusted the code to reflect his answer:

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');
        }
    });
}


推荐答案

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

JohnnyHK pointed out my error. Using the library, Async - I've adjusted the code to reflect his answer:

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');
    }
});
}

这篇关于即使我检查文档是否已存在,Mongoose仍在保存文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆