首页 > 解决方案 > 如何使用nodejs将数组推入mongoose中的数组?

问题描述

我在猫鼬中定义了一个数组。在该数组中有一些字段和一个数组。除了空的数组外,所有这些字段都已填充。现在我想将新元素推送到该数组中。以下是猫鼬中的语法:

{
    "_id" : ObjectId("5f426fb0c4057b2ae87e6a8c"),
    "hash" : "1cdde2c528d9ac6770d1cb735e89f57b99bf0bc442269013f9df492ea9a2b70ee88c1220a71ac31c650c1cda42573ef9c2f452d572d99866e8a1bd7ed5ea439a",
    "salt" : "677468d92cff400e39ed4ad484be3fb8",
    "tag" : "Client",
    "email" : "vikas.zv95@gmail.com",
    "name" : "Vikas Yadav",
    "Addtasks" : [ 
        {
            "commonID" : "2iwxtrwnap9",
            "status" : "Done",
            "Date" : "Sun Aug 23 2020 19:02:08 GMT+0530 (India Standard Time)",
            "exampleRadios" : "option1",
            "otherdetails" : "Not much thanks!",
            "website" : "dsfdd.com",
            "keywords" : "article importance, article generation, article quality",
            "words" : 12345,
            "topic" : "How article is generated?",
            "_id" : ObjectId("5f426fd8c4057b2ae87e6a90"),
            "Bigpaths" : [ 
             
            ]
        }, 
        {
            "commonID" : "xtcsrnfbvg",
            "status" : "Done",
            "Date" : "Sun Aug 23 2020 19:02:31 GMT+0530 (India Standard Time)",
            "exampleRadios" : "option1",
            "otherdetails" : "haha great!",
            "website" : "grumpytext.com",
            "keywords" : "anxiety disorders for children, anxiety disorders for adults",
            "words" : 2345,
            "topic" : "How to fight anxiety?",
            "_id" : ObjectId("5f426fefc4057b2ae87e6a94"),
            "Bigpaths" : [ 
               
            ]
        }
    ],
    "__v" : 0
}

这次我只想推送 Addtasks 数组的 Bigpaths 数组。下面是我正在尝试的代码:

var filesArray = req.files;
var Bigpaths2 = [];
   

   filesArray.forEach(element => {


     paths = {
      "path": element.path,
      "name": element.filename
        };

  Bigpaths2.push(paths);
  });
User.updateMany({'Addtasks.commonID':cid}, {$push: {Addtasks.Bigpaths: Bigpaths2}},
  function (error, WriterData) {
        if (error) {
            console.log("error");
        }  else {
  console.log("Task added for the writer.")
  }
  });

我收到此错误:

\Desktop\grumpytext\routes\index.js:254
User.updateMany({'Addtasks.commonID':cid}, {$push: {Addtasks.Bigpaths: B
igpaths2}},
                                                            ^
SyntaxError: Unexpected token '.'

标签: node.jsarraysmongodbexpressmongoose

解决方案


推荐阅读