【发布时间】: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