简体   繁体   中英

Update a field to be further nested in a document - MongoDB/Node

I am writing a migration with migrate-mongo and the Node driver for Mongo which both have not-so-great documentation. I am trying to take a field and nest it one level further. Here is an example of the original structure:

{
"_id": {"$oid":"xxxxxxxx"},
"module": "lalala",
"settings": {
  "yAxis": {
    "title": {
      "text": "TITLE"
    }
  }
}

I would like to take the yAxis field and its contents and nest it under a "highcharts" field so it ends up like this:

"settings": {
  "highcharts": {
    "yAxis": {
      "title": {
        "text": "TITLE"
      }
    }
  }
}

I saw this Update field with value from a nested field and was hoping I could use that $ operator to just take the yAxis contents and stick them back in but that isn't working. (The yAxis field now just reads the string literal '$settings.yAxis')

async up(db) {
  const panels = db.collection('panels');
  await panels.updateMany({module: 'lalala'},
    {$set: {'settings.highcharts.yAxis': '$settings.yAxis'}});
  await panels.updateMany({module: 'lalala'},
    {$unset: {'settings.yAxis': ''}});

I also thought maybe I should iterate through the documents, parse them as JSON and grab the contents of yAxis, and insert that into a new 'highcharts' field, but that's using await in a forEach which doesn't work.

I ideally am doing this async so that I can do multiple operations in a single migration. Otherwise I would have to set the new 'highcharts' field in one migration and unset the old 'yAxis' in a different migration which could lead to problems if one fails but the other doesn't.

Somewhat stuck here, anything helps. Thanks!

OK I was close and I dont understand why, but putting brackets around my $set was what I needed.

await panels.updateMany({module: 'lalala'},
  [ {$set: {'settings.highcharts.yAxis': '$settings.yAxis'}} ] );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM