asynchronous callback exception while inserting object to collection in mongodb - mongodb

I am trying to insert the object in FamilyData and same object in UserData in callback function of FamilyData.But here,I am able to insert an object to FamilyData but in callback function object I am getting is null.And it is causing asynchronous callback exception.In console ,I am getting upto "user id present" with stringified object but after that "FamilyId" is not printing.There it is showing null object.
The code I have attached below:
`
registerNewUser': function (obj) {
let result=null;
result = {};
let UserData1;
try {
let userId;
let messageArray;
let FamilyEmail;
let FamilyId1;
messageArray = Meteor.Validation.Registration(obj);
if (messageArray.length > 0) {
let msg = Meteor.Utility.appendMessages(messageArray);
result.Success = false;
result.Message = msg;
} else {
result.Success = true;
result.Message = 'User added successfully';
if (!obj.check_familymember) {
userId = Accounts.createUser({
email: obj.email,
password: obj.pwd
});
if (userId != undefined) {
console.log("user id present",JSON.stringify(obj));
FamilyData.insert({
FamilyName: obj.FamilyName,
Address: obj.Address,
CreatedBy: obj.firstname,
Latitude: obj.latitude,
Longitude: obj.longitude
}, function (err, FamilyId) {
console.log("FamilyId",JSON.stringify(obj));
UserData.insert({
FirstName: obj.firstname,
LastName: obj.lastname,
Gender: obj.genderval,
DateOfBirth: obj.dob,
Email: obj.email,
Password: obj.pwd,
FamilyId: FamilyId,
UserId: userId,
});
if(err){
// throw err;
result.Message=err;
console.log("error is",err);
}
});
console.log("user created");
} else {
result.Success = false;
result.Message = 'Unable to create user ';
}
} else {
FamilyEmail = obj.FamilyEmailId;
UserData1 = UserData.findOne({
Email: FamilyEmail
});
if (UserData1 == null) {
result.Success = false;
result.Message = 'FamilyId does not exist..';
} else {
FamilyId1 = UserData1.FamilyId;
userId = Accounts.createUser({
email: obj.email,
password: obj.pwd
});
if (userId != undefined) {
UserData.insert({
FirstName: obj.firstname,
LastName: obj.lastname,
Gender: obj.genderval,
DateOfBirth: obj.dob,
Email: obj.email,
Password: obj.pwd,
FamilyId: FamilyId1,
UserId: userId
});
} else {
result.Success = false;
result.Message = 'Unable to create user ';
}
}
}
}
} catch (e) {
logError(e);
result.Success = false;
result.Message = e.message;
}
`

Meteor uses fibers to run asynchronous code
so you don't havee to use callback in db operations
try the following
let familyId = FamilyData.insert({
FamilyName: obj.FamilyName,
Address: obj.Address,
CreatedBy: obj.firstname,
Latitude: obj.latitude,
Longitude: obj.longitude
});

Related

Mongodb .post unable to add data to the collection

I am trying to take user input and then add a drug(medicine) to MongoDB. But it is not working and I am getting the error "Add proper parameter first". The user input should be patient name, drug name, dosage, frequency, adherence, and reason for not taking medicine. Please help!
app.post("/add-drug", (req, res) => {
try {
if (req.body && req.body.patient_name && req.body.drug_name && req.body.dosage && req.body.frequency && req.body.adherence && req.body.reason) {
let new_drug = new drug();
new_drug.patient_name = req.body.patient_name
new_drug.drug_name = req.body.drug_name;
new_drug.dosage = req.body.dosage;
new_drug.frequency = req.body.frequency;
new_drug.adherence = req.body.adherence;
new_drug.reason = req.body.reason;
new_drug.user_id = req.user.id;
new_drug.save((err, data) => {
if (err) {
res.status(400).json({
errorMessage: err,
status: false
});
} else {
res.status(200).json({
status: true,
title: 'Drug Added successfully.'
});
}
});
} else {
res.status(400).json({
errorMessage: 'Add proper parameter first!',
status: false
});
}
} catch (e) {
res.status(400).json({
errorMessage: 'Something went wrong!',
status: false
});
}
});
The model file looks like this:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
drugSchema = new Schema( {
patient_name: String,
drug_name: String,
dosage: Number,
frequency: Number,
adherence: Number,
reason: String,
user_id: Schema.ObjectId,
}),
drug = mongoose.model('drug', drugSchema);
module.exports = drug;
it is supposed to be <field>:<value> inside your app.post method, not <field>=<value>
The new_drug.save() method is asynchronous, so it returns a promise that you can await on:
app.post("/add-drug", async(req, res) => {
//...
await new_drug.save();
})

Firebase Callable Function returning nill data

I'm doing firebase auth on the backend and it's working. It's correctly creating the user and I get the UUID in the console log, however when I try to send back the user's UUID I get a nill response. I've already tried all the solutions on other stackoverflow responses and none have worked for me.
This is my firebase callable function.
exports.create_user_auth = functions.https.onCall((data, context)=> {
const email = data.email;
const password = data.password;
return admin.auth().createUser({
email: email,
emailVerified: false,
password: password,
})
.then((userRecord) => {
// response.status(200).send("Successfully created new user: " +userRecord.uid);
console.log(`UserRecord ${userRecord}`)
console.log(`UserRecord ${userRecord.uid}`)
return userRecord.uid
})
.catch((error) => {
// response.status(400).send("Failed to create user: " + error);
return error
});
});
This is my swift code
Functions.functions().httpsCallable("create_user_auth").call(data) { (result, error) in
if result != nil {
print("Result: \(result)")
print("data", result?.data)
let userId = result!.data as? String
print("UserId: \(userId)")
// onSuccess(offerId!)
}
if error != nil {
print("Error: \(error)")
}
}
This is the new working code
exports.create_user_auth = functions.https.onCall(async (data, context)=> {
const email = data.email;
const password = data.password;
var uuid = ""
await admin.auth().createUser({
email: email,
emailVerified: false,
password: password,
})
.then(async (userRecord) => {
// response.status(200).send("Successfully created new user: " +userRecord.uid);
console.log(`NEW UPDATE`)
console.log(`UserRecord ${userRecord}`)
console.log(`UserRecord ${userRecord.uid}`)
uuid = userRecord.uid
// return userRecord.uid
})
.catch((error) => {
// response.status(400).send("Failed to create user: " + error);
return error
});
console.log(`UUID OUTSIDE: ${uuid}`)
return uuid
});

when updation occurs new password get inserted and authentication fails (in mean stack application)

password saved on db (when user registered) changes when user update his/her details.I have done below code for updation in routes/api.js
var User = require('../models/user');
module.exports = function(router) {
router.put('/profileupdation2/:ssn/:firstname/:lastname/:username/:email/:age/:phno',function(req,res) {
var ssn1 = req.params.ssn;
var fname = req.params.firstname;
var lname = req.params.lastname;
var username = req.params.username;
var email1 = req.params.email;
var age1 = req.params.age;
var phno1 = req.params.phno;
User.findOne({ssn:ssn1}, function(err,user) {
if(err) throw err;
console.log(user);
if(!user){
console.log('No user found');
} else {
user.ssn = ssn1;
user.firstname = fname;
user.lastname = lname;
user.username = username;
user.email = email1;
user.age = age1;
user.phno = phno1;
user.update(function(err) {
if (err) {
console.log(err);
} else {
console.log('updated!!!');
}
});
}
});
});
return router; //returns the router object to server
};

Why is the arr array not in the users object after creation of it?

I am try to make arr a array that every user has but is never sent to client side. A day ago the it stopped being put into user objects on user create. Here is the code; thanks.
client
Template.create_user.events({
'click #create-user-button': function() {
var username = $("#username").val();
var password = $("#password").val();
var email = $("#email").val();
var bio = $("#bio").val() || "";
if (!username || !password || !email) {
} else {
Accounts.createUser({
username: username,
password: password,
email: email,
arr:[],
profile: {
bio: bio
}
});
}
}
});
server/user.js
Accounts.onCreateUser(function(options, user) {
if (options.profile)
user.profile = options.profile;
return user;
});
Accounts.createUser takes an object with at most 4 fields: username, email, password, and profile. You are passing in arr, which is being ignored by the server. You have two options:
Put arr inside of the profile object.
Add arr to the user in the Accounts.onCreateUser callback.
option 1:
Accounts.createUser({
username: username,
password: password,
email: email,
profile: {
bio: bio,
arr: []
}
});
option 2:
Accounts.onCreateUser(function(options, user) {
if (options.profile)
user.profile = options.profile;
user.arr = [];
return user;
});
In that case, you will also need to publish the extra field so that the client can see it. See the users section of the docs. Specifically:
// server
Meteor.publish("userData", function () {
if (this.userId) {
return Meteor.users.find({_id: this.userId}, {fields: {arr: 1}});
} else {
this.ready();
}
});
// client
Meteor.subscribe("userData");

MeteorJS: Collection always returns count of 0

I have an app that has a collection called Cities.
Right now, all I am trying to do is to get the consoleto print the count of documents in the collection, but it only returns 0
Client.js
Meteor.subscribe('cities');
Meteor.autorun(function() {
Meteor.subscribe('jobs', Session.get('currentIndustryOnet'));
});
Meteor.startup(function(){
if(!Session.get('jobsLoaded'))
Session.set('jobsLoaded', true);
if(! Session.get('map')) {
gmaps.initialize();
}
Deps.autorun(function(){
console.log(Cities.find().count())
});
});
If I log into the mongo shell and run:
db.cities.find().count()
The count returned is 29467, so I know there are records that exist. Not sure what I am doing wrong here
Code Structure:
project_dir/client/client.js
Meteor.subscribe('cities');
Meteor.autorun(function() {
Meteor.subscribe('jobs', Session.get('currentIndustryOnet'), function(){
console.log(Cities.find({}).count());
});
});
project_dir/server/server.js
Meteor.publish('jobs', function(onet_code){
var cursor, options = {sort: {"dateacquired": -1}};
if(onet_code && onet_code != 'all'){
cursor = Jobs.find({onet: onet_code}, options);
} else {
cursor = Jobs.find({}, options);
}
return cursor;
});
Meteor.publish('cities');
project_dir/model.js:
Cities = new Meteor.Collection("cities");
Jobs = new Meteor.Collection("jobs");
Jobs.allow({
insert: function(id) {
return false;
},
update: function(id, options) {
return true;
}
});
createJob = function(options) {
var id = Random.id();
var onet = Session.get('currentIndustryOnet')
Meteor.call('createJob', _.extend({_id: id}, options));
return id;
}
Meteor.methods({
createJob: function(options) {
var id = options._id || Random.id();
Jobs.insert({
_id: id,
lat: options.lat || '',
lng: options.lng || '',
title: options.title,
url: options.url,
company: options.company,
address: options.address,
dateacquired: options.dateacquired,
onet: options.onet,
jvid: options.jvid
});
return id;
}
})
You need to publish your cities collection:
Instead of :
Meteor.publish("cities")
You should have :
Meteor.publish("cities", function() {
return Cities.find()
});