How to push an object coming from postman to nested object? - javascript

I'm having a problem in pushing these data to an nested object.
Here is what I put on postman as JSON format:
"productId":"621256596fc0c0ef66bc99ca",
"quantity":"10"
here is my code on my controller
module.exports.createOrder = async (data) => {
let product = data.productId;
let oQuantity = data.quantity
let totAmount = data.totalAmount
return User.findById(product).then(user =>{
user.userOrders.products.push({productId:product})
user.userOrders.products.push({quantity:oQuantity})
if (user) {
return user.save().then((savedOrder,err)=>{
if (savedOrder) {
return user
} else {
return 'Failed to create order. Please try again'
}
})
} else {
return "try again"
}
})
}
my schema is:
userOrders:[
{
products:[
{
productName:{
type: String,
required: [true, "UserId is required"]
},
quantity:{
type: Number,
required: [true, "Quantity is required"]
}
}
],
totalAmount:{
type: Number,
required: [true, "Quantity is required"]
},
PurchasedOn:{
type: Number,
default: new Date()
}
}
]
})
i got these error on my CLI
user.userOrders.products.push({productId:product})
^
TypeError: Cannot read properties of null (reading 'userOrders')
Currently i wish to just put these data from postman to the nested object but i think im not using the push use-case well. Any tips?

user is not found and contains null. User.findById(product) returns an empty result. The ID product can't be found in User. First, check if the user was found, then, push the products:
module.exports.createOrder = async (data) => {
let product = data.productId;
let oQuantity = data.quantity
let totAmount = data.totalAmount
return User.findById(product).then(user => {
if (!user) {
return "try again";
}
user.userOrders.products.push({productId:product})
user.userOrders.products.push({quantity:oQuantity})
return user.save().then((savedOrder, err) => {
if (savedOrder) {
return user;
} else {
return 'Failed to create order. Please try again';
}
});
});
};

Related

React useState not updating all property except when using loops

I am validating form from server side. once I get error message, I wants to show error message on respective textbox field's error message
client side Object
const formFields = {
firstName: {
helperText: '',
error: false
},
lastName: {
helperText: '',
error: false
},
emailID: {
helperText: '',
error: false
},
phoneNo: {
helperText: '',
error: false
},
password: {
helperText: '',
error: false
},
confirmPassword: {
helperText: '',
error: false
}
}
Server side response object after validation
const responseError = errorData.response.data.errors //below object is the response
//{
//"LastName": ["Enter LastName"],
//"FirstName": ["Enter FirstName"],
//"ConfirmPassword": ["Enter Confirm Password","confirm password do not match"]
//}
useState
const [inpValues, setInpValues] = useState(formFields)
Conditions to update
if ClientSideObj.key === responseObj.key then setInpValues of error and helperText field
const responseError = errorData.response.data.errors
console.log(responseError)
var FormFieldName = ""
for (keys in formFields) {
console.log('FormField keys = ' + keys)
for (var errorKeys in responseError) {
if (keys.toLowerCase() === errorKeys.toLowerCase()) {
console.log('* MATCHED FIELDS = ' + errorKeys)
//Matched 3 fields(LastName,FirstName,ConfirmPassword) successfully
FormFieldName = keys
setInpValues(prevInpValues => ({
...prevInpValues,
[FormFieldName]: {
...prevInpValues[FormFieldName],
error: true,
helperText: responseError[errorKeys]
}
})
)
console.table(inpValues)
}
}
}
Note
I go through this stack overflow already, then I passed previousState values also. still result same.
It's updating only the last for loop condition value
If the response.error object has return only one field, then it's updating that one
It's updating only the last for loop condition value
Javascript infamous Loop issue?
What is the difference between "let" and "var"?
as Miguel Hidalgo states, you should make all changes in one update:
const responseError = errorData.response.data.errors
console.log(responseError)
setInpValues(state => {
const newState = { ...state };
for (let errorKey in responseError) {
for (let formField in formFields) {
// this would be so much simpler if your properties would be in the correct case and you'd not have to do this dance with `.toLowerCase()`
if (formField.toLowerCase() !== errorKey.toLowerCase()) {
continue;
}
newState[formField] = {
...newState[formField],
error: true,
helperText
}
}
}
return newState
});
If errorKey and fieldName would be identical and you'd not have to match them case insensitive you could write this:
const responseError = errorData.response.data.errors
console.log(responseError)
setInpValues(state => {
const newState = { ...state };
for (let formField in responseError) {
newState[formField] = {
...newState[formField],
error: true,
helperText: responseError[formField]
}
}
return newState
});
What you should do in order to avoid unnecessary extra renders its to loop inside setState callback:
setInpValues(prevInpValues => {
for (const formKey in formFields) {
for (const errorKey in responseError) {
if (formKey.toLowerCase() === errorKey.toLowerCase()) {
prevInpValues[formKey] = {
...prevInpValues[formKey],
error: true,
helperText: responseError[errorKey]
}
}
}
}
return {...prevInpValues}
}

nodejs filtering an array of objects where the filtering is partially done in an async function

I've read many similar questions and have tried a bunch of code. Unfortunately, I'm not getting my code to run :-(
So, the situation is as follows: In a route of a node.js server, I have to respond with a filtered array of Objects. Unfortunately, whatever I do, I always get an empty array [] back. The filter is a bit tricky in my opinion, as it consists of a string comparison AND an async call to a library function. With the console output, I can clearly see that the correct element is found, but at the same time I see that I've already received the object...
Here is some code that exemplifies my challenge:
let testArray = [
{
id: 'stringId1',
data: {
someDoc: {
moreContent: 'Some random content',
type: 'noInterest'
}
}
},
{
id: 'stringId2',
data: {
someDoc: {
moreContent: 'Some random content',
type: 'ofInterest'
}
}
},
{
id: 'stringId3',
data: {
someDoc: {
moreContent: 'Some random content',
type: 'ofInterest'
}
}
}
]
// code from a library. Can't take an influence in it.
async function booleanWhenGood(id) {
if (id in some Object) {
return { myBoolean: true };
} else {
return { myBoolean: false };
}
}
// Should return only elements with type 'ofInterest' and that the function booleanWhenGood is true
router.get('/', function(res,req) {
tryOne(testArray).then(tryOneResult =>{
console.log('tryOneResult', tryOneResult);
});
tryTwo(testArray).then(tryTwoResult => {
console.log("tryTwoResult ", tryTwoResult);
});
result = [];
for (const [idx, item] of testArray.entries() ) {
console.log(idx);
if (item.data.someDoc.type === "ofInterest") {
smt.find(item.id).then(element => {
if(element.found) {
result.push(item.id);
console.log("ID is true: ", item.id);
}
});
}
if (idx === testArray.length-1) {
// Always returns []
console.log(result);
res.send(result);
}
}
})
// A helper function I wrote that I use in the things I've tried
async function myComputeBoolean(inputId, inputBoolean) {
let result = await booleanWhenGood(inputId)
if (result.myBoolean) {
console.log("ID is true: ", inputId);
}
return (result.myBoolean && inputBoolean);
}
// A few things I've tried so far:
async function tryOne(myArray) {
let myTmpArray = []
Promise.all(myArray.filter(item => {
console.log("item ", item.id);
myComputeBoolean(item.id, item.data.someDoc.type === "ofInterest")
.then(myBResult => {
console.log("boolean result", myBResult)
if (myBResult) {
tmpjsdlf.push(item.id);
return true;
}
})
})).then(returnOfPromise => {
// Always returns [];
console.log("returnOfPromise", myTmpArray);
});
// Always returns []
return(myTmpArray);
}
async function tryTwo(myArray) {
let myTmpArray = [];
myArray.forEach(item => {
console.log("item ", item.id);
myCompuBoolean(item.id, item.data.someDoc.type === "ofInterest")
.then(myBResult => {
console.log("boolean result", myBResult)
if (myBResult) {
myTmpArray.push(item.did);
}
})
});
Promise.all(myTmpArray).then(promiseResult => {
return myTmpArray;
});
}
Asynchronous programming is really tough for me in this situation... Can you help me get it running?
I didn't inspect your attempts that closely, but I believe you are experiencing some race conditions (you print return and print the array before the promises resolve).
However you can alwayd use a regular for loop to filter iterables. Like this:
let testArray = [
{
id: 'stringId1',
data: {
someDoc: {
moreContent: 'Some random content',
type: 'noInterest'
}
}
},
{
id: 'stringId2',
data: {
someDoc: {
moreContent: 'Some random content',
type: 'ofInterest'
}
}
},
{
id: 'stringId3',
data: {
someDoc: {
moreContent: 'Some random content',
type: 'ofInterest'
}
}
}
]
async function booleanWhenGood(id) {
if (id in { 'stringId1': 1, 'stringId2': 1 }) { // mock object
return { myBoolean: true };
} else {
return { myBoolean: false };
}
}
async function main() {
let filtered = []
for (item of testArray)
if ((await booleanWhenGood(item.id)).myBoolean && item.data.someDoc.type === 'ofInterest')
filtered.push(item)
console.log('filtered :>> ', filtered);
}
main()

Postgres "for Each" RangeError: Maximum call stack size exceeded

I'm using sequelize, and I have a function that uses findOrCreate, however it seems to throw and error "RangeError: Maximum call stack size exceeded" despite sometimes adding the entries.
The code I use is below, and I am passing it 6 tids. Does anyone know whats going on and how to resolve/prevent this?
exports.sqlAddTags = async function(did, tids) {
try {
await sequelize.authenticate();
const promises = [];
tids.forEach(t =>{
console.log(did, t)
promises.push(FB_Tag.findOrCreate({
where: {
did: did,
tid: t
}
}));
});
return await Promise.all(promises);
} catch (e) {
console.log(e.message)
}
};
My model:
FB_Tag.init({
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
did: {
type: Sequelize.STRING,
allowNull: false,
},
tid: {
type: Sequelize.STRING,
allowNull: false
},
}, {
sequelize,
modelName: 'fb_tag',
timestamps: false
});
EDIT: Seems with just 1 tid, it also throws this error
If the item already exists, I seem to get this message. Not sure if this is normal?
CREATE OR REPLACE FUNCTION pg_temp.testfunc(OUT response "public"."fb_tags", OUT sequelize_caught_exception text) RETURNS RECORD AS $func_66aef14340b2417dabf18d3cdfafa589$ BEGIN INSERT INTO "public"."fb_tags" ("i
d","did","tid") VALUES (DEFAULT,'jcBUnwocFS9I7RekMZHJ','7AQS1zPkLIUsSfx8lC0a') RETURNING * INTO response; EXCEPTION WHEN unique_violation THEN GET STACKED DIAGNOSTICS sequelize_caught_exception = PG_EXCEPTION_DETAIL; END $func_66aef14340b2417dabf18d3cdfafa589$ LANG
UAGE plpgsql; SELECT (testfunc.response).*, testfunc.sequelize_caught_exception FROM pg_temp.testfunc(); DROP FUNCTION IF EXISTS pg_temp.testfunc();
I've created a test script with the same logic as above that works, so I can only put this down to be how the function is called..
const newTags = [];
const oldTags = [];
const postgresTags = []
data.tags.forEach(t => {
if(t.id === t.title) {
newTags.push(t.title)
} else {
oldTags.push(t.id);
postgresTags.push(t.id)
}
});
if(oldTags.length > 0) {
await firestoreAddTagsToDesign(context.auth.uid, oldTags, data.did, "old");
}
if(newTags.length > 0) {
const setTags = await firestoreAddNewTags(context.auth.uid, newTags, data.did);
await firestoreAddTagsToDesign(context.auth.uid, setTags, data.did, "new");
setTags.forEach(i => postgresTags.push(i.id));
}
await sqlAddTags(data.did, postgresTags);

How to search in a REST API express with multiple fields

I would like to perform a search request like https://api.mywebsite.com/users/search?firstname=jo&lastname=smit&date_of_birth=1980
I have a User schema like:
var UserSchema = new mongoose.Schema({
role: { type: String, default: 'user' },
firstname: { type: String, default: null },
lastname: { type: String, default: null },
date_of_birth: { type: Date, default: null, select: false },
});
What I did so far with stackoverflow help:
// check every element in the query and perform check function
function search_t(query) {
return function (element) {
for (var i in query) {
if (query[i].function(element[i], query[i].value) == false) {
return false;
}
}
return true;
}
}
// prepare query object, convert elements and add check function
// convert functions are used to convert string (from the query) in the right format
// check functions are used to check values from our users
function prepareSearch(query, cb) {
let fields = {
"firstname": {
"type": "string",
"function": checkString,
"convert": convertString
},
"lastname": {
"type": "string",
"function": checkString,
"convert": convertString
},
"date_of_birth": {
"type": "date",
"function": checkDate,
"convert": convertDate
}
};
for (let k in query) {
k = k.toLowerCase();
if (!(k in fields)) {
return cb({message: "error"});
}
query[k] = {value: fields[k].convert(query[k]), function: fields[k].function};
}
return cb(null, query);
}
// linked to a route like router.get('/search/', controller.search);
export function search(req, res) {
return User.find({}).exec()
.then(users => {
return prepareSearch(req.query, (err, query) => {
if (err) {
return handleError(res)(err);
} else {
return res.status(200).send(users.filter(search_t(query)));
}
});
})
.catch(handleError(res));
}
So this code works but I don't know if it's a good thing. I have a lot of other fields to check (like gender, ....) and I don't know if it's a good thing to do it "manually".
I don't know if mongoose has any function to do it.
Should I use another method to filter / search in my users in my REST API ?
I'm pretty new here and I am not sure about how I work...
Thank you,
Ankirama

MongoDB $pull not working

I am building a Meteor app and I have Contests/Entries collections. When someone enters the contest, their user_id is pushed into the Contest.entered_users array with $addToSet. Here is the code:
entryInsert: function(entryAttributes) {
check(Meteor.userId(), String);
check(entryAttributes, {
contest_id: String
});
var user = Meteor.user();
var entry = _.extend(entryAttributes, {
user_id: user._id,
user_name: user.profile.name,
submitted: new Date(),
submitted_day: moment().format('MMM D')
});
var currentContest = Contests.findOne(entryAttributes.contest_id);
// Check to make sure that the person has not already entered the giveaway
if (currentContest.entered_users.indexOf(entry.user_id) !== -1) {
throw new Meteor.Error('invalid', "You have already entered the giveaway");
} else {
Contests.update(
currentContest._id,
{
$addToSet: {entered_users: entry.user_id},
$inc: {entries: 1}}
);
}
// Create entry in order to get the entry id
var entryId = Entries.insert(entry, function(err) {
if (err) {
alert(err.reason);
}
});
return {
_id: entryId
}
}
I want to remove a persons user_id from the Contest.entered_users array when an entry is removed. I am trying to use $pull but it doesn't appear to be working... When I remove an entry, the entry.user_id is still in the contest.entered_users array. Here is the relevant code:
'click .entry-delete': function(e, tmpl) {
e.preventDefault();
var currentEntry = this;
var currentEntryId = this._id;
var contestId = Contests.findOne(currentEntry.contest_id);
// Update the contest by removing the entry's useer_id from entered_users
Meteor.call('contestRemoveEntry', contestId, currentEntry, function(error) {
if (error) {
alert(error.reason);
}
});
Meteor.call('entryRemove', currentEntryId, function(error) {
if(error) {
alert(error.reason);
}
});
}
Here is the contestRemoveEntry method:
contestRemoveEntry: function(contestId, currentEntry) {
Contests.update({ _id: contestId }, { $pull: { entered_users: currentEntry.user_id } } );
}
Any ideas as to why this is not working? I've tried other SO solutions but nothing seems to be working.
It appears that this is the correct way to make $pull work:
Contests.update(contestId, { $pull: { entered_users: currentEntry.user_id } } );

Categories