How to deal with Unhandled rejection SequelizeConnectionError: connect ETIMEDOUT - javascript

The following code is a project which parses directories of CSV files to input into a MySQL database. It often works, however I am plagued by an ETIMEDOUT error. I am a junior developer and am unsure how to handle this situation, or why it is occurring. It may be because I am parsing too much information at once. Any advise on how to handle this would be greatly appreciated.
const app = require('express')();
var fs = require('fs');
var Papa = require('papaparse');
var Sequelize = require('sequelize');
var _ = require('underscore');
var mainDirectory = ['./Relay-Data'];
var sequelize = new Sequelize('relay_cloud','root','admin',{
host: 'localhost',
dialect: 'mysql',
logging: false,
pool: {
max: 5,
min: 0,
idle: 50000,
acquire: 50000,
evict: 50000,
handleDisconnects: true
}
});
var Relay = sequelize.define('relay',{
Timestamp:{
type: Sequelize.DATE,
field: 'Timestamp',
},
Identifier:{
type: Sequelize.INTEGER,
field: 'Identifier',
},
Building:{
type: Sequelize.STRING,
field: 'Building',
},
Device_Type:{
type: Sequelize.STRING,
field: 'Device_Type'
},
Unit:{
type: Sequelize.STRING,
field: 'Unit'
},
Energy:{
type: Sequelize.DECIMAL,
field: 'Energy'
},
Volume:{
type: Sequelize.DECIMAL,
field: 'Volume'
},
File_Name:{
type: Sequelize.STRING,
field: 'File_Name'
}
},{
timestamps: false,
freezeTableName: true
});
Promise.all(mainDirectory.map(function(main) {
return new Promise(function(resolve, reject) {
fs.readdir(main, function(er,dirs){
if (er) {
return reject(er);
}
for(var i = 0; i < dirs.length; i++){
dirs[i] = mainDirectory + "/" + dirs[i];
}
resolve(dirs);
});
}).then(function(dirs){
return Promise.all(dirs.map(function(dir) {
return new Promise(function(resolve, reject) {
fs.readdir(dir, function(er, files) {
if (er) {
return reject(er);
}
resolve(files);
});
}).then(function(files) {
return Promise.all(files.map(function(file) {
return new Promise(function(resolve, reject) {
fs.readFile(dir + '/' + file, 'utf-8', function(er, content) {
if (er) {
return reject(er);
}
var data_obj = Papa.parse(content,{
quotes: false,
delimiter: ";",
});
data_array = data_obj.data;
output_data_array = [];
for(var i = 10; i < data_array.length; i++){
if(data_array[i][0] !== "" ){
output_data_array.push({
"Timestamp" : data_array[i][0],
"Identifier" : data_array[i][1],
"Building" : file.split( "_" )[ 1 ],
"Device_Type" : data_array[i][3],
"Unit" : data_array[i][5],
"Energy" : parseFloat(data_array[i][11].replace(',','.').replace(' ', '')) || 0 ,
"Volume" : parseFloat(data_array[i][13].replace(',','.').replace(' ', '')) || 0,
"File_Name" : file
});
}
}
Relay.bulkCreate(output_data_array);
});
resolve();
});
}));
});
}));
});
})).catch(function(er) {
console.log(er);
});
app.listen(process.env.PORT || 3000, process.env.IP, function(){
console.log("Server is listening");
})

I've been facing this issue today, and this worked for me:
let sequelize = new Sequelize(dbName, dbUsername, dbPassword, {
host: dbHost,
// the rest of your sequelize configuration...
retry: {
match: [
/ETIMEDOUT/,
/EHOSTUNREACH/,
/ECONNRESET/,
/ECONNREFUSED/,
/ETIMEDOUT/,
/ESOCKETTIMEDOUT/,
/EHOSTUNREACH/,
/EPIPE/,
/EAI_AGAIN/,
/SequelizeConnectionError/,
/SequelizeConnectionRefusedError/,
/SequelizeHostNotFoundError/,
/SequelizeHostNotReachableError/,
/SequelizeInvalidConnectionError/,
/SequelizeConnectionTimedOutError/
],
max: 5
}
});

I was able to prevent the ETIMEDOUT error by doing the following:
setTimeout(function() {
Relay.bulkCreate(output_data_array);
}, 2);

Related

Envelope: Cannot read property 'id' of undefined in sails.js

Envelope: Cannot read property 'id' of undefined in sails.js
Whenever i have have send create request they give me above error,
model : Car.js
module.exports = {
attributes: {
name: {
type: 'string',
required: true,
unique: true
},
engine: {
type: 'String',
},
type: {
type: 'String'
},
colors: {
collection: 'color',
via: 'car'
}
},
};
model : Color.js
module.exports = {
attributes: {
color: {
type: 'String',
unique: true,
required: true
},
car: {
model: 'car',
required: true
}
},
};
CarController.js
please help me as fast as possible
bcz i have amateur learner in sails.js
create: async function (req, res) {
let name = req.param('name');
let engine = req.param('engine');
let type = req.param('type');
let colorName = req.param('color');
if(!name){
res.badRequest({err : 'invalid Name'});
}
if(!engine){
res.badRequest({err : 'invalid Engine'});
}
if(!type){
res.badRequest({err : 'invalid Type'});
}
if(!colorName){
res.badRequest({err : 'invalid Color Name'});
}
await Car.create({
name: name,
engine: engine,
type: type
})
.exec((err, newcar) => {
if(err) {
return res.serverError(err);
}
//Create New Color
Color.create({
color: colorName,
car: newcar.id,
})
.exec((err, _color) => {
if(err) {
return res.serverError(err);
}
})
res.send(newcar, _color);
})
},
It's look like id error, please solve as fast as possible
Lookups working in sails.js
find: async(req, res) => {
try{
let doc = await db.collection('color').aggregate([
{
$lookup: {
from: 'car',
localField: 'carID',
foreignField: 'carID',
as: 'Car'
}
}
]).toArray();
res.ok(doc);
} catch (error) {
return res.badRequest(error);
}
}

Discord.js SQLITE_ERROR: no such column: stats.guild_id

I'm making a discord bot and I have run into a run problem with database.
I have two databases: one is for keeping stats(works fine), other is configs. Whenever I run needed command and try to read data from the configs database it for some reason tries to read from the stats one. I have looked through the code and I can't seem to find the problem. When command is run, I get this in log:
SQLITE_ERROR: no such column: stats.guild_id
Here are the two files. One is for the main bot script other is command script that is run.
Main script:
const bot = new Discord.Client({disableEveryone: true});
const fs = require("fs");
const localconfig = JSON.parse(fs.readFileSync("./local-config.json", "utf8"));
const wordbanks = JSON.parse(fs.readFileSync("./modules/wordbanks.json", "utf8"));
const antilang = require("./modules/anti-lang.js");
const Sequelize = require("sequelize");
const seqStats = new Sequelize('database', 'user', 'password', {
host: 'localhost',
dialect: 'sqlite',
logging: false,
storage: './db/stats.sqlite',
});
const seqConfig = new Sequelize('database', 'user', 'password', {
host: 'localhost',
dialect: 'sqlite',
logging: false,
storage: './db/configs.sqlite',
});
const Stats = seqStats.define('stats', {
id: {
type: Sequelize.STRING,
unique: true,
primaryKey: true,
},
username: Sequelize.STRING,
xp_bal: {
type: Sequelize.INTEGER,
defaultValue: 0,
allowNull: false,
},
money_bal: {
type: Sequelize.INTEGER,
defaultValue: 0,
allowNull: false,
},
warn_bal: {
type: Sequelize.INTEGER,
defaultValue: 0,
allowNull: false,
},
mute_bal: {
type: Sequelize.INTEGER,
defaultValue: 0,
allowNull: false,
},
kick_bal: {
type: Sequelize.INTEGER,
defaultValue: 0,
allowNull: false,
},
ban_bal: {
type: Sequelize.INTEGER,
defaultValue: 0,
allowNull: false,
},
}, {
timestamps: false,
});
const Configs = seqConfig.define('configs', {
server_id: {
type: Sequelize.INTEGER,
unique: true,
primaryKey: true,
},
guild_id: {
type: Sequelize.STRING,
unique: true,
allowNull: false,
},
prefix: {
type: Sequelize.STRING,
defaultValue: "$",
allowNull: false,
},
configs_active: {
type: Sequelize.STRING,
defaultValue: "NO",
allowNull: false,
},
stats_active :{
type: Sequelize.STRING,
defaultValue: "NO",
allowNull: false,
},
defaultRole: {
type: Sequelize.STRING,
defaultValue: "NONE",
allowNull: false,
},
modLogsChannel: {
type: Sequelize.STRING,
defaultValue: "NONE",
allowNull: false,
},
economyLogsChannel: {
type: Sequelize.STRING,
defaultValue: "NONE",
allowNull: false,
},
welcomeChannel: {
type: Sequelize.STRING,
defaultValue: "NONE",
allowNull: false,
},
chatLogsChannel: {
type: Sequelize.STRING,
defaultValue: "NONE",
allowNull: false,
},
todoChannel: {
type: Sequelize.STRING,
defaultValue: "NONE",
allowNull: false,
},
suggestionsChannel: {
type: Sequelize.STRING,
defaultValue: "NONE",
allowNull: false,
},
bugReportsChannel: {
type: Sequelize.STRING,
defaultValue: "NONE",
allowNull: false,
},
}, {
timestamps: false,
});
bot.on("ready", async () => {
antilang(bot);
Stats.sync();
Configs.sync();
console.log(`${bot.user.username} is online!`);
});
//==============Command Files Section================
bot.commands = new Discord.Collection();
bot.aka = new Discord.Collection();
fs.readdir("./commands", (err, files) => {
if (err) console.log(err)
let jsfile = files.filter(f => f.split(".").pop() === "js")
if (jsfile.length <= 0) {
return console.log("[LOGS] Couldn't Find Commands!");
}
jsfile.forEach((f, i) => {
let pull = require(`./commands/${f}`);
bot.commands.set(pull.config.name, pull);
pull.config.aka.forEach(aka => {
bot.aka.set(aka, pull.config.name)
});
});
});
//==============Bot Joins Guild Section================
bot.on("guildCreate", async (guild) => {
console.log("Joined new guild: " + guild.name + " with ID: " + guild.id + ".");
const configs = await Configs.findOne({where: { server_id: guild.id } });
if (!configs){
Configs.create({
server_id: guild.id,
guild_id: `${guild.id}`,
});
console.log(`No records found for ${guild.name}(${guild.id}). Created new entry.`);
}
});
//==============Bot Leaves Guild Section================
bot.on("guildDelete", async (guild) => {
console.log("Left guild: " + guild.name + " with ID: " + guild.id + ".");
});
//==============Member Joins Guild Section================
bot.on("guildMemberAdd", async (member) => {
console.log(`New member ${member.user.username} has joined guild ${member.guild.name}.`);
const configs = await Configs.findOne({where: { server_id: member.guild.id } });
const configs_active = configs.get("configs_active");
if(configs_active == "YES"){
const defaultRole = configs.get("defaultRole");
let defRole = member.guild.roles.cache.find(r => r.name === defaultRole);
member.roles.add(defRole);
const guild_id = configs.get("guild_id");
const welcomeChannel = configs.get("welcomeChannel");
if(welcomeChannel == "NONE"){
return;
} else {
bot.guilds.resolve(guild_id).channels.resolve(welcomeChannel).send(`A member has joined: ${member.user.username} :partying_face:`);
}
}
const stats = await Stats.findOne({ where: { id: member.id } });
if (!stats) {
Stats.create({
id: member.id,
username: member.user.username,
});
console.log(`No records found for ${member.user.username}(${member.user.id}). Created new entry.`);
}
});
//==============Member Leaves Guild Section================
bot.on("guildMemberRemove", async (member) => {
if(member.id != bot.user.id){
console.log("Member " + member.user.username + " has left the guild.");
const configs = await Configs.findOne({where: { server_id: member.guild.id } });
const configs_active = configs.get("configs_active");
if(configs_active == "YES"){
const guild_id = configs.get("guild_id");
const welcomeChannel = configs.get("welcomeChannel");
if(welcomeChannel == "NONE"){
return;
} else {
bot.guilds.resolve(localconfig.logsguild).channels.resolve(localconfig.welcomeChannel).send(`A member has left: ${member.user.username} :disappointed_relieved:`);
}
}
} else {
return;
}
});
//==============onMessage Section================
bot.on("message", async message => {
if(message.author.bot){
return;
} else if (message.channel.type === "dm") {
return message.channel.send("Please only speak to me in servers that I'm in.\nI'm not made to be your personal servant!");
} else if (message.mentions.has(bot.user)){
let index = Math.floor(Math.random() * wordbanks.tagreplies.length);
message.channel.send(wordbanks.tagreplies[index]);
}
let xpAmount = Math.floor(Math.random() * (15 - 1) + 1);
let moneyAmount = Math.floor(Math.random() * (15 - 1) + 1);
const stats = await Stats.findOne({ where: { id: message.author.id } });
if (!stats) {
console.log(`Can't find any database records for ${message.author.username}(${message.author.id}).`)
} else {
const money_bal = stats.get("money_bal");
const xp_bal = stats.get("xp_bal");
if(xp_bal == "Infinity"){
console.log(`${message.author.username} has infinite xp.`);
const editMoney = await Stats.update({ money_bal: money_bal + moneyAmount }, { where: { id: message.author.id } });
} else if(money_bal == "Infinity"){
console.log(`${message.author.username} has infinite money.`);
const editXP = await Stats.update({ xp_bal: xp_bal + xpAmount }, { where: { id: message.author.id } });
} else if(money_bal == "Infinity" && xp_bal == "Infinity"){
console.log(`${message.author.username} has infinite money & xp.`);
} else {
const editMoney = await Stats.update({ money_bal: money_bal + moneyAmount }, { where: { id: message.author.id } });
const editXP = await Stats.update({ xp_bal: xp_bal + xpAmount }, { where: { id: message.author.id } });
}
}
bot.emit('checkLang', message, Stats, Configs);
//==============Command Call Section================
let prefix = localconfig.prefix;
if (message.author.bot || message.channel.type === "dm") return;
if (!message.content.startsWith(prefix)) return;
let args = message.content.slice(prefix.length).split(' ');
let cmd = args.shift().toLowerCase();
let commandfile = bot.commands.get(cmd.slice(0)) || bot.commands.get(bot.aka.get(cmd.slice(0)))
if (commandfile) commandfile.run(bot, message, args, Stats, Configs)
});
bot.login(localconfig.logintoken);
Command Script:
const Discord = require("discord.js");
const Sequelize = require("sequelize");
module.exports.run = async (bot, message, args, Configs) => {
const configs = await Configs.findOne({where: { guild_id: message.guild.id } });
const configs_active = configs.get("configs_active");
const stats_active = configs.get("stats_active");
const prefix = configs.get("prefix");
const defRole = configs.get("defaultRole");
const modLogsChannel = configs.get("modLogsChannel");
const economyLogsChannel = configs.get("economyLogsChannel");
const welcomeChannel = configs.get("welcomeChannel");
const chatLogsChannel = configs.get("chatLogsChannel");
const todoChannel = configs.get("todoChannel");
const suggestionsChannel = configs.get("suggestionsChannel");
const bugReportsChannel = configs.get("bugReportsChannel");
let testEmbed = new Discord.MessageEmbed()
.setTitle("BOT TEST")
.setDescription("Config Test For Bot")
.addField("Configs Active:", configs_active)
.addField("Stats Active:", stats_active)
.addField("Prefix:", prefix)
.addField("Default Role:", defRole)
.addField("ModLogs ID:", modLogsChannel)
.addField("Economy ID:", economyLogsChannel)
.addField("Welcome ID:", welcomeChannel)
.addField("ChatLogs ID", chatLogsChannel)
.addField("TODO ID:", todoChannel)
.addField("Suggestions ID:", suggestionsChannel)
.addField("Bug Reports ID:", bugReportsChannel)
message.channel.send({embed: testEmbed});
}
module.exports.config = {
name: "test",
aka: ["testing"],
usage: "$test",
description: "Test",
accessableby: "Anyone"
}
Thanks for help in advance!

Is there any function in KeystoneJS to load only related items for one category?

I'm creating a website with tours, that must be specified by categories, but I don't know how to load only tours related to categories. I tried to load them with find().where() but I get all tours loaded in all 3 categories.
KeystoneJS doesn't have documentation about any sort methods, I found only two examples, that don't work for me.
My trips.js:
let keystone = require('keystone');
let async = require('async');
exports = module.exports = function (req, res) {
let view = new keystone.View(req, res);
let locals = res.locals;
// Set locals
locals.section = 'tours';
locals.filters = {
trip: req.params.trip,
};
locals.data = {
trips: [],
category: [],
};
view.on('init', function (next) {
keystone.list('TripCategory').model.find().sort('name').exec(function (err, results) {
locals.data.category = results;
next(err);
async.each(locals.data.category, function (category, next) {
keystone.list('Trip').model.find().where('category', category.name).exec(function (err, results) {
locals.data.trips = results;
console.log(locals.data.trips);
next(err);
});
});
});
});
view.render('trips');
};
My Trip.js:
let keystone = require('keystone');
let Types = keystone.Field.Types;
let Trip = new keystone.List('Trip', {
map: { name: 'title' },
singular: 'Trip',
plural: 'Trips',
autokey: { path: 'slug', from: 'title', unique: true },
});
Trip.add({
title: { type: String, required: true },
content: {
brief: { type: Types.Html, wysiwyg: true, height: 150 },
extended: { type: Types.Html, wysiwyg: true, height: 400 },
},
category: { type: Types.Relationship, ref: 'TripCategory' },
duration: { type: Types.Html, wysiwyg: true },
distance: { type: Types.Html, wysiwyg: true },
price: { type: Number },
images: { type: Types.CloudinaryImages },
coverImage: { type: Types.CloudinaryImage },
});
Trip.register();
My TripCategory.js:
let keystone = require('keystone');
let Types = keystone.Field.Types;
let TripCategory = new keystone.List('TripCategory', {
autokey: { from: 'name', path: 'slug', unique: true },
});
TripCategory.add({
name: { type: String, required: true, unique: true },
description: { type: Types.Html, wysiwyg: false, height: 500 },
});
TripCategory.relationship({ ref: 'Trip', path: 'trips', refPath: 'category' });
TripCategory.register();
You should just be able to use a regular find query, along with populate.
keystone.list('Trip').model.find()
.populate({path: 'category', options: {sort: {'name'}}})
.exec(function(err, results) {
locals.data.trips = results;
})
This will get all trips, along with their corresponding category info, and sort them by the category name. If this syntax gives you issues (due to keystonejs using an older version of mongoose) try some of the different syntax versions that have continued to evolve. Here's a post that details them

No matching document found for id error

I am facing two issues with the below code
Upon saving the document after put API call,it's throwing a message ' No matching document found for id \"59c6607a1608fe26e8c7f574\"" '
If required attribute value for each field is set as true then mongoose is throwing a validation error message stating that path not found.For eg if ii set addressLine1: { type: String, required: true } then it throws a validation message contact.addressLine1: Path contact.addressLine1 is required.However if required attribute is set to false then no validation error is thrown.
Can some one help me to correct the below code -
Model -
var localTransportSchema = new Schema({
providerID: {
type: Number,
required: true,
trim: true,
unique: false
},
name: {
type: String,
required: true,
trim: false
},
contact: {
addressLine1: {
type: String,
required: false
},
addressLine2: {
type: String,
required: false
},
city: {
type: String,
required: false
},
postalCode: {
type: Number,
required: false
},
primaryContactNumber: {
type: Number,
required: false
},
secondaryContactNumber: {
type: Number,
required: false
},
serviceActiveFlag: {
type: String,
required: false,
enum: ['Y', 'N']
},
},
vehicle: [{
vehicleType: {
type: String,
required: false,
enum: ['sedan', 'hatchback', 'suv', 'mpv', 'luxury']
},
activeFlag: {
type: String,
required: false,
enum: ['Y', 'N']
},
}]
});
Controller -
module.exports.updateLocalTransportVendorDtls = function(req, res) {
var transportSchema = new transportModel();
new Promise(function(resolve, reject) {
checkForNewVehicleType(req, function(doc) {
resolve(doc)
})
})
.then(function(doc) {
var updateJustServiceDtls = doc.split(/\|/)[2];
return addJustNewVehicleDetailsOnly(req, res)
}).then(function() {
transportSchema.save(function(error) {
if (error) {
logger.error("Error while updating record in transport details collection: - " + error.message)
return res.status(500).json({
"Message": error.message.trim()
});
}
})
}).catch(function(err) {
return res.json({
"Message": err.message
});
});
}
Function -
var addJustNewVehicleDetailsOnly = function(req, res) {
var promise = new Promise(function(resolve, reject) {
var updates = {
$set: {
"contact": {
"addressLine2": req.body['addressLine2'],
"secondaryContactNumber": req.body['secondaryContactNumber'],
"serviceActiveFlag": req.body['serviceActiveFlag']
},
"$push": {
"vehicle": {
"vehicleType": req.body['vehicleType'],
"chargePerKiloMeter": req.body['chargePerKM'],
"selfDriven": req.body['isSelfDriven'],
"additionalCharges": req.body['additionalCharges'],
"driverBata": req.body['driverBata'],
"activeFlag": req.body['vehicleActiveFlag']
}
}
}
}
transportModel.findOneAndUpdate({
"name": req.body['providerName'],
"contact.postalCode": parseInt(req.body['postalCode'])
},
updates, {
returnOriginal: false,
upsert: false
},
function(err, doc) {
if (err) {
logger.error("Error while updating record : - " + err.message);
return reject(res.status(409).json({
"Message": "Error while updating transport details for provider " + req.body['providerName'] + " in transport details table"
}));
} else if (doc === null) {
logger.error("Error while updating record in transport details : - unable to update database");
return reject(res.status(409).json({
"Message": "Error while updating transport details for provider " + req.body['providerName'] + " due to " + err.message
}));
}
return resolve();
});
})
return promise;
}

Express, Mongoose - .update() is returning null

When I am trying to update a document in my model, the .update() is returning null but the .find() method works fine.
module.exports.updateBio = function(req, res) {
var userID = req.params.id;
var objForUpdate = {};
if (!troolr.isEmptyString(req.body.profile_picture)) objForUpdate.profile_picture = req.body.profile_picture;
if (!troolr.isEmptyString(req.body.title)) objForUpdate.title = req.body.title;
if (!troolr.isEmptyString(req.body.intro)) objForUpdate.intro = req.body.intro;
if (!troolr.isEmptyString(req.body.summary)) objForUpdate.summary = req.body.summary;
if (!troolr.isEmptyString(req.body.skills)) objForUpdate.skills = req.body.skills;
if (!troolr.isEmptyString(req.body.facebook)) objForUpdate.social.facebook = req.body.facebook;
if (!troolr.isEmptyString(req.body.twitter)) objForUpdate.social.twitter = req.body.twitter;
if (!troolr.isEmptyString(req.body.linkedin)) objForUpdate.social.linkedin = req.body.linkedin;
if (!troolr.isEmptyString(req.body.website)) objForUpdate.social.website = req.body.website;
var conditions = { "_id": userID }
, setObj = { $set: objForUpdate }
, options = { multi: true };
//This throws error
// Error: { ok: 0, n: 0, nModified: 0 }
Profile.update(conditions, setObj, (err, page) =>{
if(err) throw err;
console.log(page);
});
// This works fine but it erases old values if they are empty
/* Profile.findById(userID, (error, user) => {
if(error) return res.status(500).json({ success: false, error: error });
user.bio = objForUpdate;
user.save(function(error) {
if(error) return res.status(500).json({ success: false, error: error });
return res.status(200).json({ success: true, message: "Bio successfully updated." });
});
}); */
};
// API Endpoint
http://localhost:3000/api/v1/profile/592c53b3bdf350ce004ad717/updatebio
// API Define
'use strict';
/**
* Routes for Profile Model
*
**/
var passport = require('passport');
var jwt = require('jwt-simple');
var settings = require("settings");
var profileCtrl = require(settings.PROJECT_DIR + 'routes/controllers/api/profile');
module.exports = function(app) {
app.get('/all', profileCtrl.getAll);
app.get('/:id', profileCtrl.getSingle);
app.put('/:id/updateurl', profileCtrl.updateURL);
app.put('/:id/updateaddress', profileCtrl.updateAddress);
app.put('/:id/updatebio', profileCtrl.updateBio);
}
// Model
var mongoose = require('mongoose');
// User Schema
var ProfileSchema = mongoose.Schema({
url : {
type: String,
unique: true,
},
fname: {
type: String,
required: true
},
lname: {
type: String,
required: true
},
email: {
type: String,
unique: true,
required: true
},
bio: {
profile_picture: {
type: String
},
title: {
type: String
},
intro: {
type: String
},
summary: {
type: String
},
skills: {
type: Object
},
social: {
linkedin: {
type: String
},
twitter: {
type: String
},
facebook: {
type: String
},
website: {
type: String
}
},
},
location: {
address: {
type: String
},
apt: {
type: String
},
city: {
type: String
},
state: {
type: String
},
zip_code: {
type: String
},
country: {
type: String
}
},
phone: {
type: Number
},
listings: {
type: Object
},
reviews: {
type: Object
},
verfied: {
type: Boolean,
default: false
},
// expires: {
// type: Date,
// expires: '1h',
// default: Date.now
// },
});
var Profile = module.exports = mongoose.model('Profile', ProfileSchema);
module.exports.getUserByEmail = function(email, callback){
var query = {'email': email};
Profile.findOne(query, callback);
}
module.exports.checkIfUrlExists = function(res, url, callback){
var query = {'url': url};
Profile.findOne(query, function(error, found) {
if(error) return res.status(500).json(error);
if(found) return res.status(500).json({success: false, message: "URL already exists" });
if(callback) callback();
});
}
// Document which I am trying to update
{
"_id": "592c53b3bdf350ce004ad717",
"url": "hyoh7ryb-",
"fname": "Foo",
"lname": "Bar",
"email": "foobar#gmail.com",
"__v": 0,
"verfied": false
}
Anything not defined in schema is not saved. That's what happening when you're missing bio key while preparing the objForUpdate to $set:
var objForUpdate = {};
if (!troolr.isEmptyString(req.body.profile_picture)) objForUpdate.profile_picture = req.body.profile_picture;
which should be
var objForUpdate = {
bio: {}
};
if (!troolr.isEmptyString(req.body.profile_picture)) objForUpdate.bio.profile_picture = req.body.profile_picture;
if (!troolr.isEmptyString(req.body.title)) objForUpdate.bio.title = req.body.title;
// and so on
Your save is working because of saving the object in the right keyuser.bio = objForUpdate;

Categories