【问题标题】:mongoose forEach loop and update documents one by one猫鼬forEach循环并一一更新文档
【发布时间】:2018-03-07 10:29:18
【问题描述】:

我想查询一个集合并使用我将从另一个查询中获得的某个值更新每个文档,该查询将使用返回文档中的一些信息构建。

const mongoose = require('mongoose');
const userModel = {
      country: { type: String }
      newField: { type: String } 
     };
const myUsersModel = mongoose.model('user',userModel); 
myUsersModel.find({country:"USA"}).forEach(function (doc) {

    // another query here into a relation Database:
    let anotherQuery = 'SELECT * FROM myTable WHERE name=' + doc.name;
    mySQLConnection.query(
            anotherQuery,
            function selectCb(err, results, fields) {
                if (err) {
                    console.log("ERROR: " + err.message);
                    throw err;
                }
                console.log("Got "+results.length+" Rows:");
                let updatedInfo = results.SomeField;

                // update the mongoose doc:
                doc.newField = updatedInfo;
                myUsersModel.save(doc);

            });
        mySQLConnection.end(function(err) {
          console.log("connection ended.");
        });
        mongoose.connection.close();
    });

我收到以下错误:

TypeError: myUsersModel.find(...).forEach 不是函数

【问题讨论】:

    标签: javascript sql node.js mongodb mongoose


    【解决方案1】:
    myUsersModel.find({country:"USA"})
       .then(users=>users.forEach //users might be null here btw
    

    或者如果你想保持你的回调风格

    myUsersModel.find({country:"USA"}, function(err, users) {
      if (err) throw err;
      users.forEach
    

    【讨论】:

    • 很酷,但我仍然收到另一个错误,说TypeError: myUsersModel.save is not a function,现在我应该如何保存文档?
    • @moaningalways 使用 doc.save() mongoosejs.com/docs/documents.html
    【解决方案2】:

    如果未提供回调,Model.find 将返回 Query 的实例,而不是 Array 的实例。 因此,您不能使用forEach,因为 Query 不是数组。

    【讨论】:

    • 那么您的解决方案是什么?你能给出完整的答案吗?谢谢
    • 看起来 Андрей Щербаков 已经回答了它
    • 谢谢,但是我在保存时遇到了另一个问题,说 TypeError: myUsersModel.save is not a function ,我应该如何保存文档?
    猜你喜欢
    • 1970-01-01
    • 2020-06-27
    • 2016-05-24
    • 2018-09-08
    • 1970-01-01
    • 2017-10-05
    • 1970-01-01
    • 1970-01-01
    • 2017-02-10
    相关资源
    最近更新 更多