I am facing an issue while updating data, the user is not getting updated even after I passed hardcoded data, I'm trying to pass through postman-body-formData but it's not working I'm getting undefined in the result.
User.findByIdAndUpdate({_id: '61f8f3a09cd06463942401'},
{
$set:{
name: 'demoo',
dob: new Date(params.dob),
dom: new Date(params.dom)
}
}, function (error, result) {
logger.info("#edit() : User updated successfully with results = {%j}", result,{});
done(result);
console.log('result',result);
});
}
Try to change approach and update your User manually (make sure that the parent function is declared as async):
try {
const user = await User.findById('61f8f3a09cd06463942401')
if (!user) return res.status(400).send('User not found')
user.name = 'demoo'
user.dob = new Date(params.dob)
user.dom = new Date(params.dom)
await user.save()
done(user);
} catch (err) {
return res.status(500).send('Server error')
}
Related
i am new to this , i am having problem , i have to create almost 200 users in cognito after reading data from csv file which is located in S3 bucket
the problem is , if a user already exists in Cognito , my code stop executing and give me an error "An account with the given email already exists." is there a way that i can pass the whole data. if there is user already in the cognito with the same email, it skips that user and checks for the new user data , and at the end which users are already exists in cognito .this the function to create user in cognito
here is the function for creating the cognito user
function RegisterUser(data2) {
console.log(data2[1])
for(let i=0;i<=data2.length;i++){
var attributeList = [];
var cognitoUser;
attributeList.push(new AmazonCognitoIdentity.CognitoUserAttribute({ Name: "name", Value: data2[i][0]}));
attributeList.push(new AmazonCognitoIdentity.CognitoUserAttribute({ Name: "email", Value: data2[i][1] }));
try{
return new Promise((resolve, reject) => {
userPool.signUp(data2[i][1], data2[i][2], attributeList, null, (err, result) => {
if (err) {
console.log(err.message);
reject(err);
return;
}
cognitoUser = result.user;
resolve(cognitoUser);
});
});
}catch(err){
return{
success:false,
message:err
}
}
}
}
here is the lambda handler
exports.handler = async (event, context) => {
try {
// Converted it to async/await syntax just to simplify.
const data = await S3.getObject({Bucket: 'user-data-file', Key: 'SampleCSVFile_2kb.csv'}).promise();
var data1 = Buffer.from(data.Body).toString();
var data2 = data1.split("\r\n"); // SPLIT ROWS
for (let i in data2) { // SPLIT COLUMNS
data2[i] = data2[i].split(",");
}
const userPoolResponse = await RegisterUser(data2);
}
catch (err) {
return {
statusCode: err.statusCode || 400,
body: err.message || JSON.stringify(err.message)
}
}
}
A quick google search brought this up: How to check Email Already exists in AWS Cognito?
Which sure thats Front end but your use case seem to be a quick once in a while run script, not a regular use User System - in which case, this is basic programing 101 to solve. You put another try catch around your call to register the user. You check the exception thrown, and if its 'already registered' you pass and continue in the loop without interruption. The above link can give you some idea of what to look for to determine if it is that exception or not.
iv been setting up a lambda instance, it grabs data from a few different services and then its meant to update a custom Cognito attribute for that user, that works correctly and i get the return response "{}" along and no errors so im assuming that means its working correctly, however when i check the users attributes its not returning anything?
i have triple checked that the app clients have read and write permissions, so i have no idea whats happening, everything, as far as i can tell, is working, just that the attribute isnt changing.
return new Promise((resolve, reject) => {
console.log("TestInside");
// setTimeout(function() {
console.log("TimeoutFunction");
var cognitoidentityserviceprovider = new AWS.CognitoIdentityServiceProvider();
var params = {
UserAttributes: [
{
Name: 'locale',
Value: UserFarms
},
],
UserPoolId: 'UserPoolID',
Username: UserName
};
console.log("Executing call");
const cognitoD = cognitoidentityserviceprovider.adminUpdateUserAttributes(params, function(err, data) {
if (err) {
console.log(err, err.stack); // an error occurred
//passon = err.message;
resolve('Error');
}
else {
// cognitodata = data;
console.log('Returned positive cognito admin update');
//UserName = data.Username;
//passon = data;
console.log(data);
resolve(data);
}
}).promise();
whats wrong, am i missing somthing really simple?
I am using Mongoose with MongoDB and i have found this problem. I find one object in database, then i return only the object property, but when i call the variable it returns whole object not the wanted property.
var CharacterInDbCounter = await UserModel.findOne({battletag: req.user.battletag}, function(err, user){
if (err) {
console.log(err);
} else {
return user.characters
}
})
console.log(CharacterInDbCounter);
returns:
{ _id: 5a25a14a05656b24accfe231,
id: 1234,
battletag: 'Something',
provider: 'bnet',
__v: 0,
characters:
[ 5a25a14a05656b24accfe218,
5a25a14a05656b24accfe219,
5a25a14a05656b24accfe21a,
5a25a14a05656b24accfe21b,
5a25a14a05656b24accfe21c,
5a25a14a05656b24accfe21d,
5a25a14a05656b24accfe21e,
5a25a14a05656b24accfe21f,
5a25a14a05656b24accfe220,
5a25a14a05656b24accfe221,
5a25a14a05656b24accfe222,
5a25a14a05656b24accfe223,
5a25a14a05656b24accfe224,
5a25a14a05656b24accfe225,
5a25a14a05656b24accfe226,
5a25a14a05656b24accfe227,
5a25a14a05656b24accfe228,
5a25a14a05656b24accfe229,
5a25a14a05656b24accfe22a,
5a25a14a05656b24accfe22b,
5a25a14a05656b24accfe22c,
5a25a14a05656b24accfe22d,
5a25a14a05656b24accfe22e,
5a25a14a05656b24accfe22f ] }
In order to achieve your goal you must do it in promise way
var CharacterInDbCounter = await UserModel.findOne({battletag: req.user.battletag})
.then(function(user){
return user.characters
})
console.log(CharacterInDbCounter);
Unfortunately when you use await you cannot catch errors by promise catch, you must surround your code in try/catch to catch exception and inside then check if user argument is not undefined or empty
try {
var CharacterInDbCounter = await UserModel.findOne({battletag: req.user.battletag})
.then(function(user) {
if (!user) {
// user not found
}
return user.characters
})
console.log(CharacterInDbCounter);
} catch(e) {
// catch unexpected errors
}
I am trying to find my record, update it, and save it. I can see the data updated and it can still show the updated data inside the callback of save(). However, when I go to the database, it is actually not updated:
Skills.findOne({ skillsCat: req.body.skillsCat }, (err, gets)=> {
if (err) {
res.send(err)
return
}
if (gets && gets.skillName.indexOf(req.body.skillName) !== -1) {
// Here I update my data
gets.percent[gets.skillName.indexOf(req.body.skillName)] = req.body.percent
Console.log(gets); // Here I can see the data is updated
return gets.save((err, updated)=> {
Console.log(updated); // Here I can see the data is updated
if (err) { return }
res.json({
message: 'Skill updated successfully',
data: updated
})
})
} else {
return
}
})
Is there anyone encounter similar issues before and help me out with this? Thanks.
Try below code :
gets.percent[gets.skillName.indexOf(req.body.skillName)] = req.body.percent
Console.log(gets); // Here I can see the data is updated
//Notice that 'fieldname' is the name of actual field in database
gets.markModified('fieldname');
return gets.save((err, updated)=> {
Console.log(updated); // Here I can see the data is updated
if (err) { return }
res.json({
message: 'Skill updated successfully',
data: updated
})
})
I am using mongoose with koa.js (maybe a bad choice but had to stick with it).
My initial callback function was :
var _project = yield parse(this);
var userdetails = this.req.user;
var that = this ;
//=============================================================
//FInd a user , check the project name exists under the user, if not then create one
//=============================================================
User.findOne({ '_id': userdetails._id }, function (err, user) {
if (err) {
this.body = "please login again , your session seems to have expired"
} console.log(user.projects.owner.indexOf(_project.name));
if(user.projects.owner.indexOf(_project.name) == -1) { //This means the project is not yet created
var temp_project = new Project(_project);
temp_project.save(function save() {
if(err) {
that.body = "Project coudn't be saved, Please try again sometime later";
} else {
user.projects.owner.push(_project.name);
user.save(function save() {
if (err) {
that.body = "This error is highly unlikely, yet if you see this .Please report this issue";
}
});
that.body = temp_project;
}
});
}
if(user.projects.owner.indexOf(_project.name) >= 0) { //THis means the project exists
that.body = "You have already created a project with same name, please use a different name";
console.log("you reached till here");
}
});
This should have worked in normal express world but later I realised that I need to rewrite in the forms of thunks so my current attemp is
function userfindONE(err, user) {
if (err) {
return "please login again , your session seems to have expired"
}
if(user.projects.owner.indexOf(tproject.name) == -1) { //This means the project is not yet created
var temp_project = new Project(tproject);
temp_project.save(function save() {
if(err) {
return "Project coudn't be saved, Please try again sometime later";
} else {
user.projects.owner.push(tproject.name);
user.save(function save() {
if (err) {
return "This error is highly unlikely, yet if you see this .Please report this issue";
}
});
return temp_project;
}
});
}
if(user.projects.owner.indexOf(tproject.name) >= 0) { //THis means the project exists
return "You have already created a project with same name, please use a different name";
} else return "nothing is matching";
}
function userfindone(userdetails) {
return function(cb) {
User.findOne({ '_id': userdetails._id }, cb);
};
}
var userdetails = this.req.user;
var tproject = yield parse(this);
But this returns the user details from the User.findone from the first mongoose call.
and anything else seems to have ignored. Thanks
this.body = yield userfindone(userdetails)(userfindONE) ;
Take a look at node-thunkify. It should be as simple as wrapping your schema's functions with it.
With Mongoose 3.9.x you can simply yield user.save(), check in your package.json you have installed the unstable release.