javascript - Mongoose 正在保存文档,即使我检查文档是否已经存在

标签 javascript mongodb mongoose

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

奇怪的是,如果我再次运行提要, 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 提要时:

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 指出了我的错误。我调整了代码以反射(reflect)他的回答:

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 - 我调整了代码以反射(reflect)他的回答:

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

关于javascript - Mongoose 正在保存文档,即使我检查文档是否已经存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49639236/

相关文章:

mongodb - 在 Mongoose 中复制数据库

javascript - 使用 CSS 编辑生成的 SVG 属性可以在 Firefox 中使用,但不能在 Chrome 中使用

javascript - Spotify json 响应包含换行符?

javascript - Bootstrap 箱元素选择

node.js - 输入是自动关闭的,不应有内容 Jade-Lang 问题

mongodb - 为登录用户创建个人收藏

node.js - 使用 Mongoose 重复​​项目

javascript - 连接数据库时最好使用 include 或 include_once

node.js - 对象不存在-Mongodb

node.js - 查询Mongoose中的多个子文档元素