子文档的Mongoose数组未保存在父文档中

时间:2017-09-20 09:59:44

标签: node.js mongoose

const KeyContactsPersonsSchema = new Schema({
  name: {
    required: true,
    type: String
  },
  contactNumber: {
    required: true,
    type: String
  },
  email: {
    required: true,
    type: String
  }
});

上面的定义模式已经包含在下面的模式keyContactsPersons属性

const CompanySchema = new Schema({
  name: {
    type: String,
    required: true,
    unique: true,
    trim: true
  },
  address: {
    type: String,
    required: true,
    trim: true
  },
  contactNumber: {
    type: String,
    required: true,
    trim: true
  },
  logo: {
    type: String,
    required: true,
    trim: true
  },
  keyContactsPersons: [KeyContactsPersonsSchema],
  billingDetails: {
    type: String,
    required: true,
    trim: true
  },
  assignedEmployee: {
    type: Schema.Types.ObjectId,
    required: true,
    trim: true
  },
  status: {
    type: Boolean,
    default: false,
    required: true,
    trim: true
  }
}, {
  timestamps: true
});

最后保存模型 传递给CompanyModel的JSON对象就像。虽然我试图保存它,但它给我一个错误,如

  

keyContactsPersons.0.email:路径email是必需的。,   keyContactsPersons.0.contactNumber:路径contactNumber是必需的。,   keyContactsPersons.0.name:路径name是必需的。

"company":{
        "name":"Leafy Code",
        "address":"Hokandara",
        "contactNumber":"075227785",
        "logo":"/logo",
        "billingDetails":"billingDetails",
        "assignedEmployee":"5997e71ab6a13500018106b9",
        "status": true,
        "keyContactsPersons": [
            {
                "name":"demo person",
                "contactNumber":"0771568952",
                "email":"testmail@gmail.com"
            }   
        ]
    }


const newCompany = new CompanyModel(company);
newCompany.save();

1 个答案:

答案 0 :(得分:0)

我假设您的问题中包含的代码中公司变量在此处传递, CompanyModel(公司)包含对象 {“company”: {...}}

您的架构没有公司属性,因此对象应该是这样的:

const company = {
  "name": "Leafy Code",
  "address": "Hokandara",
  "contactNumber": "075227785",
  "logo": "/logo",
  "billingDetails": "billingDetails",
  "assignedEmployee": "5997e71ab6a13500018106b9",
  "status": true,
  "keyContactsPersons": [{
    "name": "demo person",
    "contactNumber": "0771568952",
    "email": "testmail@gmail.com"
  }]
}

const newCompany = new CompanyModel(company)
newCompany.save()