简体   繁体   English

使用 mongoose 和 node express 查找一个集合中的所有文档,更改数据并保存到另一个集合中

[英]Find all documents in one collection, change data and save into another collection using mongoose and node express

I'm trying get select data from 1 collection, remove the fields I don't need, and add some new fields, and passing the data needed which is being replicated on each document for the new fields, and save them into a different collection.我正在尝试从 1 个集合中获取 select 数据,删除我不需要的字段,并添加一些新字段,并传递在每个文档上为新字段复制的所需数据,并将它们保存到不同的集合中.

Am I getting close or am I way off?我是接近还是远离? Any help would be appreciated.任何帮助,将不胜感激。

router.post('', (req, res, next) => {
    const taskDay = req.body.taskDay;
    switch (taskDay) {
        case 'taskSunday':
            MasterTask.find({taskSunday: true}).forEach(tempData => {
                const taskSheet = new Tasksheet({
                    taskDate: req.body.taskDate,
                    taskTicket: req.body.taskTicket,
                    taskTime: tempData.taskTime,
                    taskCompany: tempData.taskCompany,
                    taskDescription: tempData.taskDescription,
                    taskCompleted: req.body.taskCompleted,
                    taskComments: req.body.taskComments,
                    taskCompletedBy: req.body.taskCompletedBy,
                    taskTimeStamp: req.body.taskTimeStamp,
                    taskKnowledgeTitle: tempData.taskKnowledgeTitle,
                    taskKnowledgeUrl: tempData.taskKnowledgeUrl,
                    taskType: tempData.taskType
                }); 
                Tasksheet.insertMany(taskSheet).then(result => {
                    console.log(result);
                    res.status(200).json({message: 'task sheet created'})
                });
            });
            break;

Sample Data being pulled in find:在 find 中提取的示例数据:

    _id: "5f0acb7209e5981d10bb765a",
    taskTime: "00:00",
    taskCompany: "CompanyName",
    taskDescription: "Some Needed Daily Task",
    taskSunday: true,
    taskMonday: true,
    taskTuesday: true,
    taskWednesday: true,
    taskThursday: true,
    taskFriday: true,
    taskSaturday: true,
    taskDisable: false,
    taskEndOfMonth: null,
    taskKnowledgeTitle: "Some Title",
    taskKnowledgeUrl: "Some URL",
    taskForSpecificDays: null,
    taskType: "Core",
    __v: 0
  }

Data transformation that I'm trying to save to new collection:我试图保存到新集合的数据转换:

  {
    id: "mongooseID",
    taskTicket: "",
    taskDate: null,
    taskTime: "00:00",
    taskCompany: "somename",
    taskDescription: "This is an example description of a task.  This is going to be an extra long line of text to test.",
    taskCompleted: false,
    taskComments: "",
    taskCompletedBy: "",
    taskTimeStamp: "",
    taskKnowledgeTitle: "Test",
    taskKnowledgeUrl: "http://www.google.com",
    taskType: "Core"
  }

Try this.尝试这个。

MasterTask.find(
{
    taskSunday: true
},
function(err, tempData) {
    let taskSheet = [];
    tempData.forEach(t => {
        taskSheet.push({
            taskDate: req.body.taskDate,
            taskTicket: req.body.taskTicket,
            taskTime: t.taskTime,
            taskCompany: t.taskCompany,
            taskDescription: t.taskDescription,
            taskCompleted: req.body.taskCompleted,
            taskComments: req.body.taskComments,
            taskCompletedBy: req.body.taskCompletedBy,
            taskTimeStamp: req.body.taskTimeStamp,
            taskKnowledgeTitle: t.taskKnowledgeTitle,
            taskKnowledgeUrl: t.taskKnowledgeUrl,
            taskType: t.taskType
        })
    })

    Tasksheet.insertMany(taskSheet, (err, t) => {
        console.log(err)
        console.log(t)
    })
})

Well, you do it a bit wrong.好吧,你做的有点不对。 If you want to simply re-export your collection values (without modifying it) you'd better use such utilities like mongodump or mongoexport (depends on scenario) and then import it viamongorestore or mongoimport如果您想简单地重新导出您的集合值(不修改它),您最好使用诸如mongodumpmongoexport之类的实用程序(取决于场景),然后通过mongorestoremongoimport导入它

If you want to handle your problem with JS code, it's fine, but code above is a bit wrong, why is that?如果你想用JS代码处理你的问题,那很好,但是上面的代码有点错误,这是为什么呢? Because if you deal with real huge number of documents in a collection, this code will never be finished.因为如果你在一个集合中处理大量的文档,这段代码永远不会完成。

So it's better to use find query with a cursor, like this:所以最好使用带有 cursor 的查找查询,如下所示:

async function t () {
   try {
        await collection_name.find({taskSunday: true}).lean().cursor({batchSize: 10}).eachAsync(async (document) => {
                /**
                * Your could write any logic here related with your document
                */
                const taskSheet = new Tasksheet({
                    taskDate: document.taskDate,
                    taskTicket: document.taskTicket,
                    taskTime: document.taskTime,
                    taskCompany: document.taskCompany,
                    taskDescription: document.taskDescription,
                    taskCompleted: document.taskCompleted,
                    taskComments: document.taskComments,
                    taskCompletedBy: document.taskCompletedBy,
                    taskTimeStamp: document.taskTimeStamp,
                    taskKnowledgeTitle: document.taskKnowledgeTitle,
                    taskKnowledgeUrl: document.taskKnowledgeUrl,
                    taskType: document.taskType
                }); 
                taskSheet.save()
        }, { parallel: 10})
   } catch (e) {
       console.error(e)
   }
}

This code will be guaranteed finished, because it takes every 10 documents (it depends on {batchSize: 10} and { parallel: 10} values) from your original collection_name and insert in one-by-one in 10 streams.此代码将保证完成,因为它从您的原始collection_name中获取每 10 个文档(它取决于{batchSize: 10}{ parallel: 10}值)并在 10 个流中一个接一个地插入。 Will allows you not load all the collection in your RAM.将允许您不加载 RAM 中的所有集合。

And also allows you to modify the necessary data on-the-fly并且还允许您即时修改必要的数据

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 节点,在一个集合中的猫鼬“ findOne”在另一个集合的“查找”中 - node, mongoose 'findOne' on one collection inside 'find' of another collection 使用猫鼬快递收集 - Collection in express using mongoose 使用 Mongoose 中另一个 model 的属性查找一个 model 中的所有文档 - Find all documents in one model using property of another model in Mongoose 如何将所有猫鼬文档从一个集合复制到同一数据库中的另一个集合 - How to copy all the mongoose Documents from one collection to another in same Database 使用Mongoose / Express / Node在一条POST路径中保存多个模型文档 - Save multiple model documents in one POST route with Mongoose/Express/Node 使用猫鼬中的另一个集合数组填充数据 - Populate data using another collection array in mongoose mongoDB 从一个集合中查找并保存在另一个集合中 - mongoDB find from one collection and save in another collection mongoose快递节点JS链接二合集不使用_id - mongoose express node JS link two collection without using _id 如何在 mongoose 的另一个集合中找到一个集合 - How to find a collection inside another collection in mongoose 节点/猫鼬:集合之间的同步查找/保存/删除:collection1.find(collection2.save(collection1.remove())) - Node/Mongoose: Synchronous Find/Save/Delete between Collections: collection1.find(collection2.save(collection1.remove()))
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM