【问题标题】:How to insert/add array of nested objects into mongodb database with nodejs and mongoose using body-parser如何使用body-parser使用nodejs和mongoose将嵌套对象数组插入/添加到mongodb数据库中
【发布时间】:2017-08-29 12:56:01
【问题描述】:

我正在尝试发出将数据插入 mongo 数据库的发布请求。我为此使用mongoose。我创建了mongooseSchema,如下所示-

const countrySchema = mongoose.Schema({
    country_id: {
      type : Number,
      required: true,
      unique : true
    },
    country_name : {
      type : String,
      required : true,
      unique : true
    },
    country_description : {
      type : String,
      required : true,
      unique : true
    },
    country_currency : {
      type : String,
      required : true,
      unique : true
    },
    country_capital : {
      type : String,
      required : true,
      unique : true
    },
    country_numberof_districs : {
      type : Number,
      required : true
    },
    country_createdat : {
      type : Date,
      required : true
    },
    country_districs : {
      districs : [
        {
          distric_id : {
            type : Number,
            // required : true,
          },
          distric_name : {
            type : String,
            // required : true,
          },
          distric_description : {
            type : String,
            // required : true,
          },
          distric_famous_for : {
            type : String,
            // required : true
          }
        }
      ]
    }
});

下面是我的post方法-

router.post('/addcountry', (request, response, next) => {
  
  const district = [];
  district.push({
    distric_id: request.body.distric_id,
    distric_name : request.body.distric_name,
    distric_description : request.body.distric_description,
    distric_famous_for : request.body.distric_famous_for
  });


  let newCountry = new country({
     country_id : request.body.country_id,
     country_name : request.body.country_name,
     country_description : request.body.country_description,
     country_currency : request.body.country_currency,
     country_capital : request.body.country_capital,
     country_numberof_districs : request.body.country_numberof_districs,
     country_createdat : new Date(),
     country_districs : {
       districs : [district]
     }
  });
  country.addCountry(newCountry, (err, country) =>{
    console.log('came here');
    if(err){
      response.json({
        success : false,
        message : 'failed to add country' + err
      });
    }else {
      response.json({
        success : true,
        message : 'country added successfully'
      });
    }
  });
});

我使用Postman 进行了测试。没有districs 部分,它工作正常。我试图在对象下方发布 -

{
    "country_id" : 909773,
    "country_name" : "USA",
    "country_description" : "UNITED STATRE",
    "country_currency" : "USD",
    "country_capital" : "NEWYORK",
    "country_numberof_districs" : 100,
    "country_districs": {
        "districs":
        [
            {
                "distric_id": 777,
                "distric_name" : "melbourne",
                "distric_description" : "no des",
                "distric_famous_for" : "beaches"
            },
            {
                "distric_id": 900,
                "distric_name" : "sydney",
                "distric_description" : "no des",
                "distric_famous_for" : "beaches"
            }
        ]
    }
}

结果是这样的-

{
    "_id" : ObjectId("58e37b5c3c6b07153600a7f6"),
    "country_id" : 909773,
    "country_name" : "USA",
    "country_description" : "UNITED STATRE",
    "country_currency" : "USD",
    "country_capital" : "NEWYORK",
    "country_numberof_districs" : 100,
    "country_createdat" : ISODate("2017-04-04T10:54:20.726Z"),
    "country_districs" : {
        "districs" : [
            {
                "_id" : ObjectId("58e37b5c3c6b07153600a7f7")
            }
        ]
    },
    "__v" : 0
}

注意:一开始我试了一个区,也没用。我怎样才能添加这个区域对象(可以有很多。像区域数组)。我怎样才能遍历所有的区域对象。希望您对此有所帮助。

【问题讨论】:

  • 你可以在制作国家时尝试这个 - let newCountry = new country({ country_districs : { districs : req.body.country_districts.districts } }); 以及其他字段......
  • 如果 districts 键不是您想要的,您可以通过在架构中将变量定义为数组来简单地存储对象数组,并且您可以将对象数组存储到相应的键.如果你愿意,我可以发布一个简单的例子,前提是地区不是你的强制性要求
  • 尝试将 country_districs : { districs : [district] } 更改为 country_districs : { districs : District }
  • 谢谢大家,但是如果有多个distric
  • @JyotmanSingh,它工作正常。它应该是districs : req.body.country_districts.districs。谢谢您的帮助。如果您可以将此作为我可以接受的答案。无论如何,感谢所有帮助过的人。祝你好运和欢呼!

标签: node.js mongodb mongoose mean-stack


【解决方案1】:

你能不能一边造国一边试试这个-

let newCountry = new country({ 
    country_districs : { 
        districs : req.body.country_districs.districs
     } 
}); 

连同其他领域...

【讨论】:

    猜你喜欢
    • 2018-06-22
    • 2016-10-24
    • 2021-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-25
    • 2021-09-01
    • 2018-11-10
    相关资源
    最近更新 更多