具有对象元素的嵌套数组架构将返回具有空对象的数组

时间:2019-09-24 09:12:08

标签: arrays node.js mongodb mongoose mongoose-schema

我想拥有对象数组,即teamMembers应该是一个数组,并且应该将对象作为具有属性名称和角色的元素。当我console.log(req.body)时,它不会出现任何错误。我想要的格式,但是作为对象的array元素未发布到架构中。

  _id: mongoose.Schema.Types.ObjectId,
  teamName: { type: String, unique: true },
  teamMembers: {
    name: {
      type: String, unique: true, lowercase: true, required: true
    },
    role: {
      type: String,
      enum: ['goal keeper', 'central back', 'central midfield', 'central forward', 'left wing',
        'attacking midfield', 'central forward', 'left midfielder', 'striker', 'defending', 'right midfielder'],
      required: true
    },
    type: Array
  },
  description: String,
  createdAt: { type: Date, default: Date.now() },
  updatedAt: { type: Date, default: Date.now() }
});

teamSchema.plugin(uniqueValidator); ```


I am not getting the desired result. Here is my collection from mogodb

{
"_id":{"$oid":"5d89d5da3f33f36579bfed25"},
"teamMembers":[{}],
"createdAt":{"$date":{"$numberLong":"1569314251247"}},
"updatedAt":{"$date":{"$numberLong":"1569314251247"}},
"teamName":"Arsenal",
"__v":{"$numberInt":"0"}
}
Expected result
``` "teamMembers":[{"name": "bernd leno", "role": "goal keeper"}] ```

Gotten result ``` "teamMembers":[{}] ```

Here is my below

```static async addTeam(req, res) {
    const {
      teamName, teamMembers, description
    } = req.body;
    try {
      if (!req.user.isAdmin) {
        return response(res, 404, 'error', {
          message: messages.unAuthorizedRoute
        });
      }
      const teams = new TeamModel({
        _id: new mongoose.Types.ObjectId(),
        teamName,
        teamMembers,
        description
      });
      const team = await teams.save();
      if (team) {
        return response(res, 201, 'success', { team });
      }
    } catch (error) {
      (error.errors.teamName.name === 'ValidatorError')
        ? response(res, 409, 'error', {
          message: messages.duplicateName
        })
        : response(res, 400, 'error', {
          message: messages.error
        });
    }
  }```


1 个答案:

答案 0 :(得分:0)

我的代码是正确的,我没有从邮递员正确发布对象数组。Right way to post an array of objects in postman using urlencoded

它也适用于原始的json / urlencoded

{
    "teamName": "Arsenal",
    "teamMembers": [{"name": "bernd leno", "role":"goal keeper"}, {"name": "Emiliano Martinez", "role":"goal keeper"}]
}