Mongoose模式不会使用give属性创建正确的对象

问题描述 投票:0回答:2

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

我的架构如下:

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"

}

帖子成功保存为

{
    "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
}

我们可以看到费用和合作伙伴费用缺失。这怎么发生的?以及如何解决这个问题?

如果我使用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));

谢谢你的帮助。

javascript mongoose mongoose-schema
2个回答
1
投票

有错别字

expenses: {
tyep: String
},

另一个是

partnerExpenses: {
  tyep: String
}

你可以在解决之后再试试。


1
投票

首先,让合作伙伴的收入,合作伙伴费用,费用和收入变成Integer,或者在模式定义中使用Number。

并修复错别字

expenses:{
tyep: String//must be spelt type
}
and
partnerExpenses:{
tyep: String//must be spelt type
}
© www.soinside.com 2019 - 2024. All rights reserved.