简体   繁体   中英

How to save nested array in MongoDB using Mongoose and NodeJS

Can anyone explain me how to save the nested array items into mongodb with mongoose and nodejs?.

Here is a schema I am using.

var demoSchema = ({
    "r_id": Number,
    "r_label": String,
    "entity": [{
        "d_label": String,
        "d_type": String
      }
    ]
})

And here is Nodejs function I am using to save the data into db

 app.route("/mypages/rooms")
  .post(function(req, res) {
   var db = mongoOp.demo();
   var response = {};
   req.checkBody("r_id", "Enter a valid r_id address.").notEmpty();
   req.checkBody("r_label", "Enter a valid label address.").notEmpty();

   var errors = req.validationErrors();
   if (errors) {
     console.log(errors);
     console.log(req.body);
     res.status(500);
     res.end('500 Server Error');
     //res.render('addrooms',{flag:1});
     return;
     } else {
         db.r_id = req.body.r_id;
         db.r_label = req.body.r_label;
         db.entity = req.body.entity;
         db.save(function(err) {
          if (err) {
           findfromdb(req, res, 2); //own function for implementation purpose
          } else {
           findfromdb(req, res, 1);
          }
        });
        //var middleVar = req.body.resources;
      //  console.log(middleVar[0].d_rgb);
     }
 });

set entity with array []

db.entity = [{}];

app.route("/mypages/rooms")
  .post(function(req, res) {
   var db = mongoOp.demo();
   var response = {};
   req.checkBody("r_id", "Enter a valid r_id address.").notEmpty();
   req.checkBody("r_label", "Enter a valid label address.").notEmpty();

   var errors = req.validationErrors();
   if (errors) {
     console.log(errors);
     console.log(req.body);
     res.status(500);
     res.end('500 Server Error');
     //res.render('addrooms',{flag:1});
     return;
     } else {
         db.r_id = req.body.r_id;
         db.r_label = req.body.r_label;
         db.entity = [{
                      "d_label": req.body.label_type,
                      "d_type": req.body.d_type
                     }];
         db.save(function(err) {
          if (err) {
           findfromdb(req, res, 2); //own function for implementation purpose
          } else {
           findfromdb(req, res, 1);
          }
        });
        //var middleVar = req.body.resources;
      //  console.log(middleVar[0].d_rgb);
     }
 });

The below operation adds the element label_type and d_type to entity array if they does not exist in the array, if they exists, then they won't be added

https://docs.mongodb.com/manual/reference/operator/update/addToSet/

Model.update(
    query, //  { _id: 1 }
    {
        $addToSet: {
            "enity": {
                "d_label": req.body.label_type,
                "d_type": req.body.d_type
            }
        }
    }
)

have a look at this answer

Pushing item to Mongodb collection array

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