如何使用body-parser、nodejs和mongoose将嵌套对象数组插入/添加到mongodb数据库中

3

我正在尝试进行一次Post请求,将数据插入到Mongo数据库中。为此,我使用了mongoose。我已经创建了下面这样的mongoose Schema -

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
}

注意:首先我尝试了一个区,但它也没有起作用。我该如何添加这个区域对象(可能有多个,比如区域数组),并如何遍历所有区域对象。希望你能帮助我。


1
你能试着在创建国家时加入以下代码吗 - let newCountry = new country({ country_districs : { districs : req.body.country_districts.districts } });,同时也要包括其他字段... - Jyotman Singh
如果districts键不是您必须要的,则可以通过将架构中的变量定义为数组来简单存储对象数组,并将其存储到相应的键中。如果您愿意,我可以提供一个简单的示例,但前提是districts不是必备条件。 - Ajitej Kaushik
尝试将以下代码从:country_districs : { districs : [district] }改为:country_districs : { districs : district } - Cédric De Dycker
谢谢大家,但如果有多个“区”怎么办? - caldera.sac
1
@JyotmanSingh,它运行良好。应该是districs:req.body.country_districts.districs。感谢您的帮助。如果您能将此作为答案,我可以接受。无论如何,感谢所有帮助过我的人。祝你好运,干杯! - caldera.sac
非常感谢,我的回答在你的问题中。 - iamkdblue
1个回答

1
你能试着完成以下代码,同时创建国家 -
let newCountry = new country({ 
    country_districs : { 
        districs : req.body.country_districs.districs
     } 
}); 

与其他字段一起...

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接