After update my sails (0.10-rc5),
I encountered a problem in beforeCreate function :
beforeCreate : function(values, next){
console.log("Called beforeCreate User ");
console.log(values);
if(!values.password || values.password !== values.confirmation){
return next({
err : ["Password doesn't match password confirmation"]
});
}
bcrypt.genSalt(10, function(err, salt){
console.log("call within bcrypt");
if (err) return next(err);
bcrypt.hash(values.password, salt, function(err, hash){
if(err) return next(err);
values.password = hash;
});
});
Access.findOne()
.where({ level : values.level })
.exec(function(err, level){
console.log("call within findOne");
if(err) return next(err);
values.level = level.id;
});
console.log("after");
console.log(values);
next();
}
However, the output of the above function is as following :
Called beforeCreate User
{ firstName: 'Quad',
lastName: 'Doe',
email: '11#11.com',
password: '123456',
confirmation: '123456',
level: 'admin',
id: '2fa1ba1a-ae1c-4380-9107-3c1f6e8eafb3',
online: false }
after
{ firstName: 'Quad',
lastName: 'Doe',
email: '11#11.com',
password: '123456',
confirmation: '123456',
level: 'admin',
id: '2fa1ba1a-ae1c-4380-9107-3c1f6e8eafb3',
online: false }
call within bcrypt
call within findOne
As you can see, somehow bcrypt.genSalt(.....){} and Access.findOne(...){} were not called prior to after, which is supposed to.
What you are seeing is asynchronous code in action...
Node/Sails does not wait for your callbacks to fire before moving on to the the next task.
You need to "nest" your callbacks so that console.log("AFTER") is called within the last callback.
Take a look at async. It's designed for these types of problems.
Or...
Look into fibers
Related
I have this:
var id = req.body.id;
var query = {'_id': req.body.id, 'site': req.body.location, 'content': req.body.services, 'updatedByCNUM': req.body.cnum};
ServicesModel.findOneAndUpdate(query, id, {upsert: true}, function(err, doc) {
if (err) return res.send(500, {error: err});
return res.send('Succesfully saved.');
});
console.log(req.body.Services, req.body.location)
I am new to mongoose, and I am trying to do an update query. I basically have the ID of the document, so I want to find it, and then update it with the new values (all being based into query). How can I do this? This above is not working, it says :
TypeError: Cannot convert undefined or null to object
thanks 4 the help
ServicesModel.findOneAndUpdate(
{_id : req.body.id},
{ $set: { site: req.body.location, content: req.body.services, updatedByCNUM: req.body.cnum } },
, {upsert: true, new: true}, function(err, doc) {
if (err) return res.send(500, {error: err});
return res.send('Succesfully saved.');
});
var id = req.body.id;
var query = {'_id': req.body.id, 'site': req.body.location, 'content': req.body.services, 'updatedByCNUM': req.body.cnum};
ServicesModel.findOneAndUpdate(
{_id : req.body.id},
{ $set: { query} },
function(err, doc) {
if (err) return res.send(500, {error: err});
return res.send('Succesfully saved.');
});
Note: $set replaced every data there before. to add a new data on the previous one you need to use $pull or $push. you can check the docs here
i'm working in a node project and need help.
I have callback function, that executes the method findOne, have o result, but I can't change a property of the result.
Ex. Data
{
name: "John",
age: 30,
}
Ex. Callback Function.
this._userRepository.findOne({}, (err, user) => {
if (err) {
return callback({ code: 404, message: "User not found" }, []);
}
user.name = "edson";
return callback("", user);
});
But user name not change in the return.
Ex. Result
{
name: "John",
age: 30,
}
Expected outcome
{
name: "edson",
age: 30,
}
You need to use user.save() before returning anything as given below,
user.name = "edson";
user.save();
return callback("", user);
OR use findOneAndUpdate() as given below
const filter = {};
const update = { name : "edson"};
this._userRepository.findOneAndUpdate(filter, update, {upsert: true}, function(err, doc) {
if (err) return res.send(500, {error: err});
return res.send('Succesfully saved.');
});
Refer https://mongoosejs.com/docs/tutorials/findoneandupdate.html for further details
are you actually trying to update the value of the user in your database? If so, I think you would need to call user.save()
Try wrapping your code in an async function, then running the following code
await this._userRepository.findOneAndUpdate({}, {$set: { name: 'edson' }});
The findOneAndUpdate method takes a filter and an object wrapped in a $set key. This method is a lot quicker.
var databaseRef = firebase.database().ref("Test_Applicants/");
databaseRef.push({
firstname: first_name,
middlename: middle_name,
lastname: last_name,
university: university_full_name,
email: email_address,
phone: phone_number,
date: getDate(),
docs: docURL
}, function(error){
//Callback failed
console.error(error);
});
Is this the right approach? How do I receive a variable or an argument from Firebase through a callback or through any other way to confirm that the data was written successfully? I'd like to upload a file if request is successful or return an error message to the user if the write fails.
This should work
var databaseRef = firebase.database().ref("Test_Applicants/");
databaseRef.push({
firstname: first_name,
middlename: middle_name,
lastname: last_name,
university: university_full_name,
email: email_address,
phone: phone_number,
date: getDate(),
docs: docURL
}, function(error){
if (error) {
console.error(error)
return
}
console.log('Push successful')
//add upload function here
});
You can listen child events in this case using following
databaseRef.on('child_added', function(data) {
console.log(data);
});
More info: https://firebase.google.com/docs/database/web/lists-of-data#listen_for_child_events
databaseRef.push().set({name:"john doe",telephone:"25400000000"}).catch((error)=>console.log(error))
I'm using react-native-google-signin to achieve google login function. After setting up all the configuration steps, I'm able to get 'user' from GoogleSignin.signIn().then((user) => {...}.
Now I want to check whether this user has already used 'this' google account. Because if yes, I don't need to create the user data in the firebase database. But if not (first time), I need to create the user data inside the Google signin function. Here is my code.
import fire from '../../firebase'
.. ..
GoogleSignin.signIn()
.then((user) => {
console.log('get user'); // I can get user here
// This firebase function can't be called (no reaction)
fire.database().ref('Users').child(user.id).once('value', snapshot => {
console.log('inside function'); // can't log it
if(!snapshot.val()) {
console.log('new'); // can't log it
fire.database().ref('Users').child(user.id).child('User_Data').set({
username: user.name,
email: user.email,
avatar: user.photo
});
}
else {
console.log('old'); // can't log it
fire.database().ref('Users').child(user.id).child('User_Data').update({
username: user.name,
email: user.email,
avatar: user.photo
});
}
});
})
.catch((err) => {
console.log('WRONG SIGNIN', err);
})
.done();
I can only get the 'user' data. No new Google email is created in my Firebase Authentication screen. Also, no new user data is created in my database.
Does anyone have the same issue or the solution? Thanks for any help or idea!
I don't use React so this might not help, but have you tried to re-factor your code to something like this;
function googleSignIn() {
GoogleSignin.signIn()
.then(validateSignIn) // Might need to be `this.validateSignIn`
.catch((err) => {
console.log('WRONG SIGNIN', err);
})
.done();
}
function validateSignIn(user) {
console.log('get user'); // I can get user here
// This firebase function can't be called (no reaction)
fire.database().ref('Users').child(user.id).once('value', snapshot => {
console.log('inside function'); // can't log it
if(!snapshot.val()) {
console.log('new'); // can't log it
fire.database().ref('Users').child(user.id).child('User_Data').set({
username: user.name,
email: user.email,
avatar: user.photo
});
}
else {
console.log('old'); // can't log it
fire.database().ref('Users').child(user.id).child('User_Data').update({
username: user.name,
email: user.email,
avatar: user.photo
});
}
}
This way the validateSignIn function is in it's own function and not encapsulated by your thenable object.
Using MongoJS: https://github.com/mafintosh/mongojs
Finds everything
db.users.find({}, function(err,users){
if (err) throw err;
console.log(users);
})
Returns the user. looks great
[{ _id: 53f2faa6aed1689e84982b8b,
facebook: {
email: 'myname#gmail.com',
name: 'Juan Atkins',
id: '764969936' },
__v: 0
}]
When I try to find that user by his id: failed
db.users.findOne({
_id: '53f2faa6aed1689e84982b8b'
}, function(err, user) {
if (err) throw err;
console.log(user);
});
returns []
I know there is data in the DB. I've tried searching by a different key (like name). Why can't it find the data?
you have to use ObjectId: http://mongodb.github.io/node-mongodb-native/api-bson-generated/objectid.html
db.users.findOne({
_id: new ObjectID('53f2faa6aed1689e84982b8b')
}, function(err, user) {
if (err) throw err;
console.log(user);
});