Эй, поэтому я пытаюсь разрешить пользователям редактировать свои профили. Тем не менее, некоторые поля не всегда существуют в документе, если они не добавляют это поле. Вот как я сейчас вызываю запрос, но получаю сообщение об ошибке, если поле не существует.Как разрешить пользователям обновлять свой профиль?
Вот код для файла маршрутов:
User.findByIdAndUpdate(req.signedCookies.userid,{
firstName: req.body.firstName.toLowerCase(),
lastName: req.body.lastName.toLowerCase(),
email: req.body.email.toLowerCase(),
firstNameTrue: req.body.firstName,
lastNameTrue: req.body.lastName,
emailTrue: req.body.email,
emailList: req.body.newEmail,
phone: req.body.phone,
phoneList: req.body.newphone,
socialAccounts: {socialAccount: req.body.socialAccount, socialAddress: req.body.socialAccountNew},
currentCity: req.body.currentCity,
birthday: new Date(req.body.birthday)
}, function(err, user) {
console.log('here1');
if(err) {
console.log("post2");
console.log(err);
res.render('editUserProfileError', {title: 'Weblio'});
} else {
console.log("post3");
res.redirect('userProfile');
}
});
};
Ошибки я получаю:
[TypeError: Cannot read property 'constructor' of undefined]
Я использую NodeJS с мангустами для MongoDB. У меня есть все поля в схеме mongoose, но они не сохраняются в db, если они не добавляются вручную пользователями.
То, что я пытался, но, кажется, большая боль, чтобы перебрать все значения полей и увидеть, какие из них существуют, бросьте их в массиве затем запросить массив со
Вот одно решение, я попробовал то есть не работает правильно, так как мне нужно что-то, чтобы позволить «:», чтобы пройти через ...
var values = [
firstNameVal = req.body.firstName.toLowerCase(),
lastNameVal = req.body.lastName.toLowerCase(),
emailVal = req.body.email.toLowerCase(),
firstNameTrueVal = req.body.firstName,
lastNameTrueVal = req.body.lastName,
emailTrueVal = req.body.email,
emailListVal = req.body.newEmail,
phoneVal = req.body.phone,
phoneListVal = req.body.newphone,
currentCityVal = req.body.currentCity,
birthdayVal = new Date(req.body.birthday)
];
var keyIcons = [
firstName,
lastName,
email,
firstNameTrue,
lastNameTrue,
emailTrue,
emailList,
phone,
phoneList,
currentCity,
birthday
];
var existValues =[];
for(var x = 0; x <keyIcons.length; x++) {
for(var i = 0; i < values.length; i++) {
if(values[i] === undefined) {
(console.log('undefined'))
} else {
existValues.push({keyIcons[i] : values[i]});
}
};
}
var socialAccountsVal = {socialAccount: req.body.socialAccount, socialAddress: req.body.socialAccountNew}
if(socialAccountsVal.socialAccount === undefined) {
} else {
existValues.push(socialAccounts);
};
Другое решение, которое я мог бы быть в состоянии сделать это запрос пользователя док, а затем посмотреть, какие значения доступны, но я на самом деле путают о том, как это сделать ...
Кроме того, я чувствую, что должен быть более простой способ сделать это?
EDIT
Вот моя схема:
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
ObjectId = mongoose.Schema.Types.ObjectId,
bcrypt = require('bcrypt-nodejs'),
SALT_WORK_FACTOR = 10;
var UserSchema = new Schema({
email: { type: String, required: true, lowercase:true, index: { unique: true } }, //might have to take off lowercase
emailTrue: { type: String},
emailPrivate: {type: Boolean},
emailList: {type: Array},
password: { type: String, required: true },
firstName: {type: String, lowercase:true, required: true, index: true},
firstNameTrue: { type: String},
lastName: {type: String, lowercase:true, required: true, index: true},
lastNameTrue: { type: String},
phone: {type: Number, required: true},
phonePrivate: {type: Boolean},
phoneList: {type: Array},
birthday: {type: Date, required: true},
birthdayPrivate: {type: Boolean},
socialAccounts: {type: Array},
currentCity: {type: String},
date_created: {type: Date},
email_confirmed: {type: Boolean},
gender: {type: Number},
currentDevice: {type: String},
last_login: {type: Date}
}, {collection: "users"});
module.exports = mongoose.model('User', UserSchema);
Как выглядит ваша пользовательская схема? –
Я добавил его внизу – Lion789
Посмотрите, помогает ли ответ на этот [вопрос] (http://stackoverflow.com/questions/16904932/mongoosejs-with-typeerror-cannot-read-property-constructor-of-undefined). –