简体   繁体   English

使用 mongoose 更新具有不同值的 mongodb 子文档

[英]Update mongodb subdocuments with different values using mongoose

I am using mongodb in my application as backend database.我在我的应用程序中使用 mongodb 作为后端数据库。 And trying to update the sub-documents of a document with different values using mongoose.并尝试使用 mongoose 更新具有不同值的文档的子文档。

Below is the sample schema for the document:以下是文档的示例架构:

'use strict';
 const mongoose = require('mongoose');

 const activitiesSchema = new mongoose.Schema({
   activityId : {
     type: String
   },
   name: {
     type: String,
   },
   points : {
     type : String
   }
 });

 const sampleSchema = new mongoose.Schema(
 {
   userId: {
     type: String,
     require: true,
   },
   userName: {
     type : String,
   },
   activities: {
     type: [activitiesSchema],
   },
   createdTime: {
     type : Date,
     default: Date.now,
   }
 },
);
const Sample = mongoose.model('Samples', sampleSchema, 'Samples');
module.exports = Sample;

I want to update the name to run if the activityId is 001 and, if the activity id is 002 I want the name to be update to walk .如果activityId001 ,我想更新要runname ,如果活动 id 为002 ,我希望将名称更新为walk

Is this possible to do in single database find and update operation?这可以在单个数据库查找和更新操作中完成吗?

Thank you,谢谢,
KK KK

You can use pipelined form of update function, like this:您可以使用流水线形式的update function,如下所示:

db.collection.update({},
[
  {
    "$set": {
      "activites": {
        $map: {
          input: "$activites",
          as: "item",
          in: {
            activityId: "$$item.activityId",
            points: "$$item.points",
            name: {
              $switch: {
                branches: [
                  {
                    case: {
                      $eq: [
                        "$$item.activityId",
                        "001"
                      ]
                    },
                    then: "run"
                  },
                  {
                    case: {
                      $eq: [
                        "$$item.activityId",
                        "002"
                      ]
                    },
                    then: "walk"
                  },
                  
                ],
                default: "$$item.name"
              }
            }
          }
        }
      }
    }
  }
],
{
  multi: true
})

Playground link .游乐场链接

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

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