Reputation: 595
Mongoose not saving the correct Schema. Attributes are missing in the new- created object.
My schema is as follows:
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
}
});
And the code for creating a new object is :
new Profile(profileFields)
.save()
.then(profile => {
//res.json(profileFields);
res.json(profile);
})
.catch(err => {
res.json(err);
});
The data in profileFeild are as follows:
{
"user": "5cbf0d03b6a1d33d085c5a41",
"handle": "aaaaaaaaaaaaa",
"dateOfBirth": "02/02/2019",
"income": "600",
"expenses": "300",
"partnerIncome": "900",
"partnerExpenses": "200"
}
The post successfully save as
{
"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
}
Which we can see expenses and partnerExpenses are missing. How did this happen? And how to fix this problem?
If I use findOneAndUpdate to update, and then send the same profileFields data, all the fields will appear like the following(which is the expected result in the first time).
{
"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
}
By the way, the code for updating is here:
Profile.findOneAndUpdate(
{ user: req.user.id },
{ $set: profileFields },
{ new: true }
).then(profile => res.json(profile));
Thanks for any assistance.
Upvotes: 0
Views: 180
Reputation: 461
First of all lets make the Partner income, partner expenses, expenses and income into Integer, or a Number in the schema definition.
and fix the typos in
expenses:{
tyep: String//must be spelt type
}
and
partnerExpenses:{
tyep: String//must be spelt type
}
Upvotes: 1
Reputation: 522
There are typos
expenses: {
tyep: String
},
and another one is
partnerExpenses: {
tyep: String
}
can you please try after fixing that.
Upvotes: 1