Why not all values store in mongodb? - node.js

I want to store form data in "moongodb" with MEAN APPLICATION
When I post values of form through my Angular form or using postman all values not stores even not creating any space for them.
Here is Course Model
const mongoose = require('mongoose');
const CourseSchema = mongoose.Schema({
degprog:String,
session:String,
semester:String,
c_code:String,
c_title:String,
c_hours:String,
c_goals:String,
m_quiz:Number,
m_assign:Number,
m_lab:Number,
m_mid:Number,
m_final:Number,
m_total:Number,
c_coprdinator:String,
c_url:String,
c_catelog:String,
c_tbook:String,
c_reference:String,
teacher:{
type:mongoose.Schema.Types.ObjectId,
ref:"teacher",
}
});
module.exports = mongoose.model('course', CourseSchema);
This is course controller file
const Teacher = require('../models/teacher.model.js');
const mongoose = require('mongoose');
// Create and Save a new Course
exports.create = async (req, res) => {
if (!req.body.courseCode) {
return res.status(400).send({
message: "Note Course Code can not be empty"
});
}
//searching for a teacher to add course
const teacher = await Teacher.findOne({ _id: req.params.teacherId });
// Create a Course
const course = new Course();
course._id = mongoose.Types.ObjectId(),
course.degprog = req.body. degreeProgram;
course.session = req.body.session;
course.semester = req.body.semester;
course.c_code = req.body.courseCode;
course.c_title = req.body.courseTitle;
course.c_hours = req.body.creditHours;
course.m_quiz = req.body.quiz;
course.m_assign = req.body.assignment;
course.c_coprdinator = req.body.courseCoordinator;
course.c_url = req.body.url;
course.c_catelog = req.body.courseCatelog;
course.c_tbook = req.body.textbook;
course.c_reference = req.body.reference;
course.c_goals = req.body.goals;
course.teacher = req.body.teacherId;
course.m_lab = req.body.lab;
course.m_mid = req.body.mid;
course.m_final = req.body.final;
course.m_total = req.body.total;
//save course in dataBase and attach to particular teacher
await course.save();
await teacher.courses.push(course._id);
await teacher.save();
res.send(course);
};
This one is routing file
app.post('/teacher/:teacherId/course', course.create);
Only till the "URL" values stores. why the remaining values not saving?

incoming req.body values were not matching , i did fix it with guide of #DanStarns after console.log incoming values were not matching with schema therefore values were not storing and not creating any space for them.
here Is Working solution
const Teacher = require('../models/teacher.model.js');
const Course = require('../models/course.model');
const mongoose = require('mongoose');
// Create and Save a new Course
exports.create = async (req, res) => {
if (!req.body.courseCode) {
return res.status(400).send({
message: "Note Course Code can not be empty"
});
}
//searching for a teacher to add course
console.log(req.body);
const teacher = await Teacher.findOne({ _id: req.params.teacherId });
// Create a Course
const course = new Course();
course._id = mongoose.Types.ObjectId(),
course.degprog = req.body. degreeProgram;
course.session = req.body.session;
course.semester = req.body.semester;
course.c_code = req.body.courseCode;
course.c_title = req.body.courseTitle;
course.c_hours = req.body.creditHours;
course.m_quiz = req.body.quiz;
course.m_assign = req.body.assignment;
course.c_coordinator = req.body.courseCoordinator;
course.c_url = req.body.url;
course.c_catelog = req.body.currentCatelogDescription;
course.c_tbook = req.body.textBook;
course.c_reference = req.body.referenceMaterial;
course.c_goals = req.body.courseGoals;
course.teacher = req.body.teacherId;
course.c_pre = req.body.pre;
course.m_lab = req.body.lab;
course.m_mid = req.body.midTerm;
course.m_final = req.body.finalTerm;
course.m_total = req.body.totalMarks;
//save course in dataBase and attach to particular teacher
await course.save();
await teacher.courses.push(course._id);
await teacher.save();
res.send(course);
};

Related

Firebase Function onCreate add to new collection works, but update does not

I have this onCreate Trigger, I am using it to aggregate and add record or update record. First it takes minutes to add the record and then the update never runs just keeps adding, not sure why my query is not bringing back a record to update.
Any suggestion would be great.
exports.updateTotals = functions.runWith({tinmeoutSeconds: 540})
.firestore.document("user/{userID}/CompletedTasks/{messageId}")
.onCreate(async (snap, context) => {
const mycompleted = snap.data();
const myuserid = context.params.userID;
console.log("USER: "+myuserid);
const mygroup = mycompleted.groupRef;
const myuser = mycompleted.userRef;
const newPoints = mycompleted.pointsEarned;
console.log("POINTS: "+newPoints);
const data = {
groupRef: mygroup,
userRef: myuser,
pointsTotal: newPoints,
};
const mytotalsref = db.collection("TaskPointsTotals")
.where("groupRef", "==", mygroup)
.where("userRef", "==", myuser);
const o = {};
await mytotalsref.get().then(async function(thisDoc) {
console.log("NEW POINTS: "+thisDoc.pointsTotal);
const newTotalPoints = thisDoc.pointsTotal + newPoints;
console.log("NEW TOTAL: "+newTotalPoints);
if (thisDoc.exists) {
console.log("MYDOC: "+thisDoc.id);
o.pointsTotal = newTotalPoints;
await mytotalsref.update(o);
} else {
console.log("ADDING DOCUMENT");
await db.collection("TaskPointsTotals").doc().set(data);
}
});
});
You are experiencing this behavior because while querying for updates you are getting more than 1 document and you are using thisDoc.exists on more than one document. If you have used typescript this could have been catched while writing the code.
So for the update query, if you are confident that only unique documents exist with those filters then here’s the updated code that I have recreated using in my environment.
functions/index.ts :
exports.updateTotals = functions.runWith({timeoutSeconds: 540})
.firestore.document("user/{userId}/CompletedTasks/{messageId}")
.onCreate(async (snap, context) => {
const mycompleted = snap.data();
const myuserid = context.params.userID;
console.log("USER: "+myuserid);
const mygroup = mycompleted.groupRef;
const myuser = mycompleted.userRef;
const newPoints = mycompleted.pointsEarned;
console.log("POINTS: "+newPoints);
const data = {
groupRef: mygroup,
userRef: myuser,
pointsTotal: newPoints,
};
const mytotalsref = admin.firestore()
.collection("TaskPointsTotals")
.where("groupRef", "==", mygroup)
.where("userRef", "==", myuser);
await mytotalsref.get().then(async function(thisDoc) {
if (!thisDoc.empty) { // check if the snapshot is empty or not
const doc = thisDoc.docs[0];
if(doc.exists){
const newTotalPoints = doc.data()?.pointsTotal + newPoints;
const id = doc.id;
await db.collection("TaskPointsTotals").doc(id).update({pointsTotal: newTotalPoints});
}
} else {
await db.collection("TaskPointsTotals").doc().set(data);
}
});
});
For more information about QuerySnapshot methods check this docs

Nodejs/Express: Facing issues while working on routings

viewController.js
const Book = require('./../models/bookModel')
const APIFeatures = require('./../utils/apiFeatures.js')
exports.getOverview=async(req,res,next)=>{
const features = new APIFeatures(Book.find(),req.query).filter().paginations()
let getItAllProd = await features.getBook;
res.render('overview',{
data:getItAllProd,
title:"trending books"
})
next()
}
exports.getOneBook =async(req,res,next)=>{
const getThatBook = await Book.findOne({slug:req.params.id})
res.render('onebook',{
data:getThatBook
})
next()
}
exports.categories= async(req,res,next)=>{
const getCate = await Book.find({category:req.params.category});
res.render('overview',{
data:getCate,
name:req.params
})
next()
}
exports.paginationOfBook = async(req,res,next)=>{
let pages = req.params.page
pages = pages * 6 || 6;
const limit = 6;
let skip = pages-6;
const getlimitedbook = await Book.find({}).limit(limit).skip(skip);
res.render('overview',{
data:getlimitedbook,
})
next()
}
viewRoutes.js
const express = require('express');
const viewController = require('./../controllers/viewController')
const router = express.Router();
router.get('/overview',viewController.getOverview)
router.get('/overview/:category',viewController.categories)
router.get('/overview/:page',viewController.paginationOfBook)
router.get('/overview/:id',viewController.getOneBook)
module.exports = router;
using http://localhost:3000/overview I can get all the books and http://localhost:3000/overview/:category - using this I get the books by categories. but if I try to load the the for http://localhost:3000/overview/:page and http://localhost:3000/overview?:id - the data will not load up.. so below I did some changes in routing..
router.get('/overview',viewController.getOverview)
router.get('/overview/:id',viewController.getOneBook)
router.get('/overview/:category',viewController.categories)
router.get('/overview/:page',viewController.paginationOfBook)
Now I have access to the '/overview' and '/overview/:Id'. but not for others. the data is not loading for them. do you have any solution? so I can access all the routes.uuu
First of all please elaborate you're question more. But I think the problem is in the following line:
const getThatBook = await Book.findOne({slug:req.params.id})
edit this line to:
const getThatBook = await Book.findById(req.params.id)
and call this route like this http://localhost:3000/overview/34234232...
Or change your "id" to "slug" in the following line.
const getThatBook = await Book.findOne({slug:req.params.slug})
and call this route like this http://localhost:3000/overview/xyz_book_slug...
router.get('/overview/:slug',viewController.getOneBook)
and pass the book's slug property value when calling this route.

Cloud Functions Firestore get key value for increment

I'm trying to get the updated number for a Member Number from a document using Cloud Functions when an admin creates a user.
What should happen is when an Admin creates a user in their dashboard, the user is added to firebase, then the member number updates, and is applied to newMemNum, then updated in the user document.
My Code:
const memNumInc = admin.firestore.FieldValue.increment(1);
const memCounter = admin.firestore().collection(`mem_num`).doc(`a1lDbrsoXjfKeosEkDtw`);
memCounter.update({number: memNumInc}).then(() =>
memCounter.get()
.then((snap) => {
const id = snap.id;
const data = snap.data()
newMemNum = data['number']
console.log('New Member Number: ' + newMemNum);
return {id, ...data};
})
);
The increment goes ok (i.e. number goes up by 1 which is expected), but the next part of the code doesn't run and doesn't throw an error.
Also, the next part of the code that updates the user document doesn't fire at all, and no errors.
Entire Code:
// Create User Document onCreate
const createProfile = (userRecord) => {
const uid = userRecord.uid;
const docId = userRecord.uid;
const fullName = userRecord.displayName || 'New User';
const memStatus = 'Unfinancial';
const isAdmin = false;
const isNew = true;
const email = userRecord.email;
const photoUrl = userRecord.photoUrl;
const phone = '0444 123 456';
const createdAt = admin.firestore.FieldValue.serverTimestamp();
const memNumInc = admin.firestore.FieldValue.increment(1);
const memCounter = admin.firestore().collection(`mem_num`).doc(`a1lDbrsoXjfKeosEkDtw`);
memCounter.update({number: memNumInc}).then(() =>
memCounter.get()
.then((snap) => {
const id = snap.id;
const data = snap.data()
newMemNum = data['number']
console.log('New Member Number: ' + newMemNum);
return {id, ...data};
})
);
return afs
.collection(`users`)
.doc(docId)
.set({
uid: uid,
docId: docId,
fullName: fullName,
joined: createdAt,
memNum: newMemNum,
memStatus: memStatus,
isAdmin: isAdmin,
isNew: isNew,
email: email,
photoUrl: photoUrl,
phone: phone,
addedOn: createdAt,
updatedOn: createdAt
})
.then(() => console.log('User Creaeted Successfuly: ' + uid))
.catch((e) => console.log('User Creation Error: ' + e.message));
}
exports.authOnCreate = functions.auth.user().onCreate(createProfile);
If I remove the memCounter code, the rest executes no problem.
You have another return statement that most likely runs before the promise returned by get() is resolved. Try refactoring the code using async-await syntax as shown below:
const createProfile = async (userRecord) => {
// const vars ....
const memNumInc = admin.firestore.FieldValue.increment(1);
const memCounter = admin.firestore().collection(`mem_num`).doc(`a1lDbrsoXjfKeosEkDtw`);
// Update documents
await memCounter.update({
number: memNumInc
})
// Get update document data
const snap = await memCounter.get()
const id = snap.id;
const data = snap.data()
newMemNum = data['number']
console.log('New Member Number: ' + newMemNum);
return afs
.collection(`users`)
.doc(docId)
.set({ ... })
}
However, if multiple users are created simultaneously, there's a chance that they'll get the same newMemNum so a transaction might be useful as well.
Firestore also introduced a new COUNT() function that can be used to get total number of documents in a collection instead of incrementing the count every time.

data is not showing in Dynamodb table

i am working on lex chatbot and want to store user data in dynamodb.
here is my databaseManager.js file code
'use strict';
const { v1: uuidv1 } = require('uuid');
const AWS = require('aws-sdk');
const dynamo = new AWS.DynamoDB.DocumentClient();
module.exports.saveBookingToDatabase = async function(Arrival_city, Departure_city, Flight_type, Phone_number){
console.log('saveBookingToDatabase');
const item = {};
item.bookingId = uuidv1();
item.arrivalCity = Arrival_city;
item.departureCity = Departure_city;
item.classType = Flight_type;
item.phone = Phone_number;
const params = {
TableName: 'air_stallion',
Item: item
};
try {
let result = await dynamo.put(params)
console.log(`Saving ticket ${JSON.stringify(item)}`);
return item;
} catch(e) {
throw (e)
}
}
Table has been created but data is now showing in table
The values should not be empty, give some default values to prevent null or empty values.
For Example:
const item = {};
item.bookingId = uuidv1();
item.arrivalCity = Arrival_city || "Arr";
item.departureCity = Departure_city || "Dept";
item.classType = Flight_type || "Type";
item.phone = Phone_number || "Phone";
If the values are okay, then try with
let result = await dynamo.put(params).promise()

async/await not working with mongoose instance methods

I'm try to create user mongoose document which require a storage path. I want to await for directory to be created and path resolved. But it is not working and after user is saved, user.storagePath is still undefined. please figure out problem.
Following is code of createStorage()
const getMountRoot = require('../configuration/configuration').getMountRoot
const path = require('path')
const fs = require('fs')
const Logger = require('../configuration/configuration').getLogger
module.exports = (email, firstName, secondName) => {
email = String(email).toLowerCase().replace(/[#_\.\-]/g, '')
firstName = String(firstName).toLowerCase().replace(/[#_\.\-]/g, '')
secondName = String(secondName).toLowerCase().replace(/[#_\.\-]/g, '')
let storagePath = path.join(getMountRoot(), `${secondName}${email}${firstName}`)
return fs.promises.mkdir(storagePath, { recursive: true })
.then(() => { return storagePath })
.catch(() => {Logger.log(err); return storagePath})
}
And following is instance method
const createStorage = require('../extra/create-storage')
userSchema.methods.createStorage = async function() {
this.storagePath = await createStorage(this.email, this.firstName, this.secondName)
}
Kindly note that I call createStorage() on User instance before calling the save()
As #qqilihq figured, I need to await at instance method call. Doing that worked correctly.

Resources