如何使用Mongoose和NodeJS在MongoDB中保存嵌套数组

时间:2017-03-09 09:31:10

标签: node.js mongodb mongoose-schema

任何人都可以解释一下如何使用mongoose和nodejs将嵌套数组项保存到mongodb中吗?

这是我正在使用的架构。

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

这里是我用来将数据保存到db

的Nodejs函数
 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);
     }
 });

1 个答案:

答案 0 :(得分:0)

使用数组[]

设置实体

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);
     }
 });

以下操作将元素label_typed_type添加到实体数组中(如果它们不存在于数组中),如果它们存在,则它们不会被添加

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
            }
        }
    }
)

看一下这个答案

Pushing item to Mongodb collection array