【问题标题】:mongoose findOneandUpdate running twice inside findOne猫鼬 findOneandUpdate 在 findOne 中运行了两次
【发布时间】:2018-10-26 01:21:06
【问题描述】:

我正在使用async eachSeries 并在文档存在时对其进行更新。这是示例代码。

let a = [ 
 { user_name: "foo" } 
];
async.eachSeries(a, (doc, done) => {

    Foo.findOne(doc).lean(true).exec((err, doc) => {

        if (err) return done(err);
        Foo.findOneAndUpdate(a, {
                user_last: "bar"
            }, {
                upsert: true,
                new: true
            },
            (err, doc) => {
                if (err) return done(err);
                return done(doc);
            });
    });
}, (err) => {
    console.log(completed);
});

有时即使数组a 有一个元素,findOneAndUpdate 函数也会在一次迭代中运行两次。我正在使用node v6.10mongoose。它不会一直发生。

有没有人遇到过类似的问题。

【问题讨论】:

  • 这里不仅有几件事没有真正的意义。当然这只是一个“练习”,但如果你真的有这样结构的代码,那么你真的需要改变它。 .findOne() 然后findOneAndUpdate() 应该没有逻辑上的理由。充其量你想“循环”一些东西并根据当前文档中存在的值进行更新。但是,如果那是您“真正”尝试做的事情,那么基于这种结构的代码就是错误的方法。你最好展示你真正需要做的事情。
  • 这里也刚刚注意到您使用的是a,它是eachSeries() 中的“数组”,而不是doc,它实际上是“每个”元素。再次不清楚您是否有相同的生产代码错误,因为这显然不是您的生产代码。

标签: node.js mongoose async.js


【解决方案1】:

你可以像这样简化你的代码

let arr = [ 
    { user_name: "foo" } 
];

async.eachSeries(arr, (query, done) => {
    // note the removal of lean() as we want a document to use .save()
    Foo.findOne(query).exec((err, doc) => {
        if (err) 
            return done(err);
        // if no document is found, judging by your code you want to create a new document
        if (!doc) {
            doc = new Foo();
        }
        // at this point you will have an existing or new document
        doc.user_last = "bar";
        doc.save(done);
    });
}, (err) => {
    if (err)
        console.log(err);
    else
        console.log('completed');
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-10
    • 2021-09-25
    • 2017-10-05
    • 2015-04-05
    • 2018-07-15
    • 2020-11-13
    • 2013-06-19
    • 2013-02-13
    相关资源
    最近更新 更多