I am writing a function that is meant to add an employee to the end of a list of employees, but I continue to be met with the error in the title. I've tried to alter the code, but I'm not sure what I'm doing wrong. Here's the function:
data-service.js
module.exports.addEmployee = function(employeeData) {
employeeData.employeeNum = ++empCount;
return new Promise(function(resolve,reject) {
employees.push(employeeData);
if(employees.length == 0) {
reject("no results returned");
}
resolve(employeeData);
});
}
server.js
app.get("/employees/add", (req,res) => {
res.render("addEmployee");
});
app.post("/employees/add", (req, res) => {
console.log(req.body);
res.redirect("/employees");
});
The current function is not the root of the problem... However, you are trying to set a property on a param that you expect to be an object. But the caller has either passed a variable that has a value === undefined, or perhaps is passing no params at all ( either way, the param employeeData is undefined and you have no checks against it, thus we see the error).
Related
I am storing particular key value in Database. But, While fetching the key value, getting undefined error.
await DbHandler.fetch(codeStatus)
.then((result) => {
const codeEnabledObj = result[0];
console.log('codeEnabledObj', codeEnabledObj);
let codeEnabled = false;
if (codeEnabledObj && codeEnabledObj.length > 0) { // this code not executing at all.
codeEnabled = codeEnabledObj[0].isEnabled;
}
console.log('codeEnabled', codeEnabled); // getting false always
console.log('codeEnabledObj.length[0]', codeEnabledObj.length); // undefined
})
.catch((error) => {
});
The issue is, It's not going inside if condition and throwing error like undefined.
But, If we print the response from db fetch
'codeEnabledObj', { type: 'codeStatus', isEnabled: true } // This is my response
Any suggestions?
Objects don't have length property like an array.
codeEnabledObj.length is wrong
use this,
Object.keys(codeEnabledObj).length
EDIT :
codeEnabledObj[0].isEnabled should be only codeEnabledObj.isEnabled
There is no property length in the codeEnabledObj , Moreover its not an Array.. so modifying the condition would work, where isEmpty could be a function used from
node package as underscore
if (isEmpty(codeEnabledObj)) { // ... }
and
codeEnabledObj.isEnabled
Thanks.
I am retrieving an object with a database call, I want to access a key's value by matching that key with a variable that I have.
In my database return I get an object that looks similar to this:
{"_id":"5c840d548a7db8af2f9eefea",
"domain":"chatbotdemo.com","deliveryTime":"ba",
"emailAddress":"ab","freeDelivery":"ab","onSale":"ab"}
I have a variable:
var intent = 'emailAddress'
The variable should always exist but theres a very slight chance it may not
and it may also be null.
What I want to do is access the value from that key field that matches the var intent, or at least get the key value pair.
What I also want to do is then if it is null then call an error, my full code is below:
getClientsDialog: function (domain, intent, callback) {
MongoClient.connect('mongodb://111011001101101', function (err, client) {
if (err) throw err;
var db = client.db('10001101');
db.collection('dialog').findOne({ domain: domain}, function (err, doc) {
// here I would want to say if (!err && ****logic to check match****)
if (!err) {
callback(doc)
} else {
throw err;
callback(err)
}
client.close();
});
console.dir("Called findOne");
});
}
Any help would be greatly appreciated!
Thanks!!
Not sure if i got the problem right but in ES6 you can use a computed value as an property name. Something like this:
let serverJson = {
"_id":"5c840d548a7db8af2f9eefea",
"domain":"chatbotdemo.com","deliveryTime":"ba",
"emailAddress":"ab","freeDelivery":"ab","onSale":"ab"
};
let intent = "emailAddress";
if (serverJson[intent]!== undefined) {
}
else {
}
I have following autoform hook code. How can I get value outside of method.call.
My problem is that when I run method.call, then 'chi' value is undefined. Whereas, on server there is '1' record.But chi doesn't get 'myResult' value. If I comment out the method.call and return 'Gogo', then 'chi' gets this value correctly. Can some one guide me what I am doing wrong and how it can be rectified.
Code:
before: {
method: function(doc) {
var retVal = false ;
var pai = Q.fcall(function(){
if(!_.isEmpty(doc) && _.pick(doc, 'name') ) {
console.log('Ist level, true condition: ', doc);
return true;
}
else{
console.log('Ist level, false condition: ', doc);
return false;
}
})
.then(function(check){
console.log('Check value: ', check);
if( check ){
Meteor.call('CategoryNameAvailable', doc.name, function (error, result) {
console.log('Returned result from server', result);
if (!result) {
if(Contexts.Category.keyIsInvalid('name')){
Contexts.Category.resetValidation('name');
}
console.log('Returned result from server inside if condition ', result);
Collections.Category.simpleSchema().namedContext("CategoryInsertForm").addInvalidKeys([{
name: "name",
type: "notUnique"
}]);
console.log('Doc value in meteor call function: ', doc);
Session.set('retVal', true);
console.log('retVal value in meteor call function: ', retVal);
}
return 'myResult';
});
// return 'Gogo';
/* Meteor call End */
}
})
.then(function(chi){
console.log('Chi value: ', chi);
})
.done();
console.log('Pai value-2: ', pai);
} /* End of method */
} /* End of 'before' hook */
You could check this out https://github.com/stubailo/meteor-reactive-method
It might solve your problem
Do you think you could add in the file where you're defining your method? I had a similar problem recently attempting to do something similar, and it had to do with the formatting of my Method definition.
For me it was misplacing where I was returning data within my method definition. In another instance of another similar problem, I wasn't subscribing to the Collection on the client side.
If thats not the issue, and your call is returning data correctly, its only not passing it outside of the context of the call, you could try and use Session.set to define a session variable that can then be called whenever you need the data.
Its going to be difficult to tell exactly whats going on though without the context of the Method definition.
I have node running with express as the server side framework.
I have created the following endpoint:
app.post('/post/save', auth.auth, function (req, res) {
Post.findById(req.body._id, function (err, post) {
post = post || new Post();
post.author.name = req.user.getName();
post.author.id = req.user._id;
post.title = req.body.title;
post.body = req.body.body;
post.save(function (err, object) {
err && res.send(500);
res.status(200).send({ /*id: object._id*/ });
});
});
});
When I call this the first time, it works.
When I call this the second time, it fails. The request just keeps pending, and the object returned from the save function call is undefined.
req.body._id is undefined in both the requests. I try to create 2 new posts in a row.
What I want to do is to check if a document exist, if it does, update it and then save it, or create a new document.
I know stuff like upsert exist, but I cant use it because I need the pre-save middleware to trigger, and it only triggers before .save.
Can anyone see the error?
What if you put your logic to a callback, and then - either create or find a Post based on the request query value, passing your callback function? Just dont forget to remove this assignment: post.author.id = req.user._id;
app.post('/post/save', auth.auth, function (req, res) {
var callback = function(post) {
post.author.name = req.user.getName();
post.title = req.body.title;
post.body = req.body.body;
post.save(function (err, object) {
err && res.send(500);
res.status(200).send({ /*id: object._id*/ });
});
};
if (req.body._id) {
Post.findById(req.body._id, function (err, post) {
callback(post);
});
} else {
var post = new Post();
callback(post);
}
});
My original post worked, once I removed the unique field from the model, and dropped the collections in the database.
It might have been enough to drop the indexes; see Leonid Beschastnys comment;
when you're setting a field to be unique, Mongoose creates an unique
index on this field. This index persist in MongoDB even after removing
unique: true flag. Dropping collection indexes should resolve your
problem
How to have a helper function for routes with the req,res object built into it. for eg. if I have send an error or success message in json I have the following lines of code
console.log(err)
data.success = false
data.type = 'e'
data.txt = "enter a valid email"
res.json data
I am planning to put this in a helper function like this
global.sendJsonErr = (msg)->
data.success = false
data.type = 'e'
data.txt = msg
res.json data
But I don't have res object in the helper function how can I can get those objects, other than passing it around. As there would be moving more repeating code I would want to take out of the route.
It is more kind of macro rather than a function module.
thanks
I've written custom middleware to do similar things. Something like this:
app.use(function(req, res, next) {
// Adds the sendJsonErr function to the res object, doesn't actually execute it
res.sendJsonErr = function (msg) {
// Do whatever you want, you have access to req and res in this closure
res.json(500, {txt: msg, type: 'e'})
}
// So processing can continue
next()
})
And now you can do this:
res.sendJsonErr('oh no, an error!')
See http://www.hacksparrow.com/how-to-write-midddleware-for-connect-express-js.html for more info on writing custom middleware.
Try this out
reshelper
npm i reshelper
I don't know exactly your use case but you may want to use a middle ware.
Some examples defined here: http://www.hacksparrow.com/how-to-write-midddleware-for-connect-express-js.html but you can have a function with req and res as argument, called at each requests.
app.use(function(req, res) {
res.end('Hello!');
});
You also have access to a third argument to pass the hand to the next middle ware:
function(req, res, next) {
if (enabled && banned.indexOf(req.connection.remoteAddress) > -1) {
res.end('Banned');
}
else { next(); }
}