猫鼬模式不创建具有给定属性的正确对象

Mongoose schema does not create correct objects with the give attributes

Mongoose 没有保存正确的架构。新创建的对象中缺少属性。

我的架构如下:

const ProfileSchema = new Schema({
  user: {
    type: Schema.Types.ObjectId,
    ref: "users"
  },
  handle: {
    type: String,
    required: true,
    max: 40
  },
  dateOfBirth: {
    type: Date
  },
  expenses: {
    tyep: String
  },
  income: {
    type: String
  },
  experience: [
    {
      title: {
        type: String
      }
    }
  ],
  education: [
    {
      school: {
        type: String
      }
    }
  ],
  partner: {
    partnerIncome: {
      type: String
    },
    partnerExpenses: {
      tyep: String
    }
  },
  date: {
    type: Date,
    default: Date.now
  }
});

而创建新对象的代码是:

new Profile(profileFields)
            .save()
            .then(profile => {
              //res.json(profileFields);
              res.json(profile);
            })
            .catch(err => {
              res.json(err);
            });

profileFeild中的数据如下:

{
    "user": "5cbf0d03b6a1d33d085c5a41",
    "handle": "aaaaaaaaaaaaa",
    "dateOfBirth": "02/02/2019",
    "income": "600",
    "expenses": "300",
     "partnerIncome": "900",
     "partnerExpenses": "200"

}

post成功另存为

{
    "partner": {
        "partnerIncome": "900"
    },
    "_id": "5cbfd9b2dc38893364f25063",
    "user": "5cbf0d03b6a1d33d085c5a41",
    "handle": "aaaaaaaaaaaaa",
    "dateOfBirth": "2019-02-01T13:00:00.000Z",
    "income": "600",
    "experience": [],
    "education": [],
    "date": "2019-04-24T03:36:18.643Z",
    "__v": 0
}

其中我们可以看到 expenses 和 partnerExpenses 丢失了。这怎么发生的?以及如何解决这个问题?

如果我使用findOneAndUpdate更新,然后发送相同的profileFields数据,所有字段都会出现如下(这是第一次的预期结果)。

{
    "expenses": "300",
    "partner": {
        "partnerExpenses": "200",
        "partnerIncome": "900"
    },
    "_id": "5cbfd9b2dc38893364f25063",
    "user": "5cbf0d03b6a1d33d085c5a41",
    "handle": "aaaaaaaaaaaaa",
    "dateOfBirth": "2019-02-01T13:00:00.000Z",
    "income": "600",
    "experience": [],
    "education": [],
    "date": "2019-04-24T03:36:18.643Z",
    "__v": 0
}

对了,更新的代码在这里:

Profile.findOneAndUpdate(
          { user: req.user.id },
          { $set: profileFields },
          { new: true }
        ).then(profile => res.json(profile));

感谢您的帮助。

有错别字

expenses: {
tyep: String
},

另一个是

partnerExpenses: {
  tyep: String
}

请你修好后再试试

首先让合作伙伴收入、合作伙伴支出、支出和收入在架构定义中成为整数或数字。

并修正

中的拼写错误
expenses:{
tyep: String//must be spelt type
}
and
partnerExpenses:{
tyep: String//must be spelt type
}