【问题标题】:Mongoose schema does not create correct objects with the give attributesMongoose 模式不会创建具有给定属性的正确对象
【发布时间】:2019-09-13 06:47:51
【问题描述】:

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"

}

帖子成功保存为

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


    【解决方案1】:

    首先让我们将合作伙伴收入、合作伙伴费用、费用和收入转换为整数,或架构定义中的数字。

    并修正

    中的错别字
    expenses:{
    tyep: String//must be spelt type
    }
    and
    partnerExpenses:{
    tyep: String//must be spelt type
    }
    

    【讨论】:

      【解决方案2】:

      有错别字

      expenses: {
      tyep: String
      },
      

      另一个是

      partnerExpenses: {
        tyep: String
      }
      

      你可以在修复后尝试一下吗?

      【讨论】:

        猜你喜欢
        • 2021-05-24
        • 2012-10-28
        • 2014-11-03
        • 1970-01-01
        • 1970-01-01
        • 2014-12-28
        • 2018-02-28
        • 2016-02-12
        相关资源
        最近更新 更多