Angular6 array is not getting stored - javascript

From last couple of hours, I'm trying to set simple array but somehow its not happening.
messages : [{message: string, nickname: string, user_id: string, profile_url: string, created_at: string, type: string}];
loadMessages(channelUrl){
this.getChannel(channelUrl)
.then(channel => {
this.channel = channel;
this.getMessageList(this.channel)
.then(messageList => {
this.messageList = messageList;
console.log(this.messageList);
this.messageList.forEach((messageData)=>{
console.log(messageData.message);
this.messages.push({message: messageData.message, nickname: '', user_id: '', profile_url: '', created_at: '', type: ''});
console.log(this.messages);
});
})
.catch(error => {
return error.message;
});
})
}
last console.log is not getting printed. neither its giving any errors.
Please guide.

Champagne has helped me to find the solution. I have added try catch because of that error was not getting displayed.
this.messages
was undefined

Related

How to find a document of an ID from an array in JavaScript (Mongoose)

I have a function on my server that is supposed to get a post by its ID. The function works up until the "foundPost" constant, where I can't seem to find one of the documents from the "posts" array. I've tried substituting findOne for find and the ObjectIds work for the const 'post'.
I've double checked that post_id is 62067c1211eea1531d5872f4
Here is the function to find a post:
const postById = async (req, res) => {
const userId = req.params.userId;
const post_id = req.params.post_id;
const posts = await Post.findOne({ user: userId });
console.log(posts); //see this below
const foundPost = await posts.findOne({ "upload": post_id }); //error here
console.log(foundPost);
return res.json({ success: true, Post: foundPost });
};
Here is what 'console.log(posts)' returns:
[
{
upload: new ObjectId("623b681bdf85df9086417723"),
edited: false,
title: 'Test 1',
description: 'testing post 1',
name: 'John ',
sharedPost: 0,
},
{
upload: new ObjectId("62067c1211eea1531d5872f4"),
edited: false,
title: 'Test 2',
description: 'testing post 2',
name: 'John ',
sharedPost: 0,
}
]
I'm hoping that the function will return:
{
success: true,
{
upload: new ObjectId("62067c1211eea1531d5872f4"),
edited: false,
title: 'Test 2',
description: 'testing post 2',
name: 'John ',
sharedPost: 0,
},
}
Can anyone see why the line const foundPost = await posts.findOne({ "upload": post_id }); isn't working?
Thank you for your help.
****** Response to answer ******
Hello, thanks a lot for your answer, unfortunately it's still giving an error. Please see below the model for the code I'm using:
const PostSchema = new Schema({
user: {
type: Schema.Types.ObjectId,
ref: "user",
},
post: [
{
user: {
type: Schema.Types.ObjectId,
ref: "user",
},
upload: {
type: Schema.Types.ObjectId,
ref: "upload",
},
title: {
type: String,
},
description: {
type: String,
},
},
],
date: {
type: Date,
default: Date.now,
},
});
I noticed that you used 'userProfile.posts' which I adapted to 'userProfile.post' to match this schema. I'm also not sure if you wanted to use 'subdoc' or 'subDoc' in line 11 of your code, but I tried both with the same error for each. I determined that the code stuck at the const subDocs = userPosts.filter(filter); line. I've looked into the .filter method you've used and can't find any potential errors. Not sure what the issue is.
Thanks
The issue is that you cannot run another mongo query on objects that were result of a previous query.
//will return a single document if found, or null if not found.
const posts = await Post.findOne({ user: userId });
//this will not work because at this point 'posts' will be either a Document or null value
//So the object will not have the method 'findOne' available.
const foundPost = await posts.findOne({ "upload": post_id });
The solution is to deal correctly with the types of objects you have.
Below is a functional and safe implementation that solves your issue:
const userPosts = await Post.findOne({ user: userId }).exec();
if (!userPosts) {
// document not found with provided userId
return res.json({ success: false });
}
//here we have a Document
//check if document has 'posts' property and is an array
if (userPosts.posts) {
//filter the posts array
const filter = function(subDoc) {
return subdoc.upload === post_id
}
const subDocs = userPosts.filter(filter);
//filter returns an array, so we must check if has itens
//then we grab the first item
if (subDocs.length > 0) {
const foundPost = subDocs[0];
return res.json({ success: true, Post: foundPost });
}
//subDoc not found, return correct response
return res.json({ success: false });
}
If your Post model schema is what I'm supposing to be, this code will work perfectly.
const schema = mongoose.schema({
user: Number,
posts: [{ upload: Number }]
})
In case of error, please add the code of the model schema structure.

useState and map - React

I am using React for my FrontEnd.
I am using functional components. I am using Axios for fetching from an API.
In file GetAllSuppliers.js, I have the following:
function GetAllSuppliers(){
const [supplier, setSupplier] = useState([]);
useEffect(() => {
return axios.get(`http://localhost:8080/api/suppliers/supplier/list`)
.then((response) =>{
setSupplier((prevState) =>({ ...prevState,
id: response.data.id ,
supplierTitle: response.data.supplierTitle,
supplierFirstName: response.data.supplierFirstName,
supplierLastName: response.data.supplierLastName,
companyName: response.data.companyName,
phoneNumber: response.data.phoneNumber,
otherPhoneNumber: response.data.otherPhoneNumber,
accountNumber: response.data.accountNumber,
email: response.data.email,
address: response.data.address,
website: response.data.website,
hourlyRate: response.data.hourlyRate,
typeOfGoods: response.data.typeOfGoods,
paymentTerms: response.data.paymentTerms,
createdAt: response.data.createdAt,
notes: response.data.notes,
products: response.data.products,
components: response.data.components
}));
}).catch((error) =>{
setSupplier(error);
})
});
}
//other functions
export { GetAllSuppliers, other functions .... };
In FileB.js, I have the following code:
{GetAllSuppliers.supplier.map(t => <TableRow key={`supplier-${t.id}`} {...t} />)}
I am getting the following error:
TypeError: Cannot read property 'map' of undefined
What is a possible fix to the above error?
This happens when you're running map() on something that's undefined. 90% of the time, that means you're not handling the case that an axios call is in-progress and your variable isn't ready, yet (probably GetAllSuppliers, in this context).
Put in a conditional return that handles this case.
In your setSupplier you are setting an object but you need to return an array to map.
Something like this:
setSupplier((prevState) => {
return [
...prevState,
{
id: response.data.id,
supplierTitle: response.data.supplierTitle,
supplierFirstName: response.data.supplierFirstName,
supplierLastName: response.data.supplierLastName,
companyName: response.data.companyName,
phoneNumber: response.data.phoneNumber,
otherPhoneNumber: response.data.otherPhoneNumber,
accountNumber: response.data.accountNumber,
email: response.data.email,
address: response.data.address,
website: response.data.website,
hourlyRate: response.data.hourlyRate,
typeOfGoods: response.data.typeOfGoods,
paymentTerms: response.data.paymentTerms,
createdAt: response.data.createdAt,
notes: response.data.notes,
products: response.data.products,
components: response.data.components,
},
];
});
```

Add error in existing errors while validating object through hapi/joi

const schema = Joi.object().keys({
Id: Joi.number().required(),
CustomerName: Joi.string()
.trim()
.required()
.when('$isInValidCustomer', {
is: true,
then: //Add some error in existing error block,
}),
BankName: Joi.string().trim(),
});
const custDetail = {
Id: 2,
CustomerName: 'xyz'
BankName: ''
};
const schemaOptions = {
abortEarly: false,
context: {
isInValidCustomer: true,
},
};
const valError = schema.validate(custDetail, schemaOptions);
So, now when I validate 'custDetail' object I want following 2 errors:
- CustomerName error because 'isInValidCustomer' is true
- BankName is required
I am not able to append error for CustomerName in existing error object. If I use '.error()' then just get single error corresponding to 'CustomerName' else just getting error for BankName.
Any help is really appreciated.
This can be achieved using custom function.
const schema = Joi.object().keys({
Id: Joi.number().required(),
CustomerName: Joi.string()
.trim()
.required()
.when('$isInValidCustomer', {
is: true,
then: Joi.any().custom(() => {
throw new Error('Invalid Customer');
}),
}),
BankName: Joi.string().trim(),
});

Converting circular structure to JSON ( where is the circulation happening? )

Getting the error TypeError: Converting circular structure to JSON on an object which doesn't have circular references.
I have tested the object in the console and had it stringified without a problem.
Even when I console log the object before passing it into the POST request, I get it stringified without a problem.
So I don't understand that on my Node server it throws this error when it gets to placing it into the request.
I have tried using npm packages flatted and yarn add json-stringify-safe, neither of which has helped.
Could it perhaps be caused by the request itself?
Here is the file contents:
const { inventorysource: { API_channel_ID, API_channel_ID_sandbox } } = require("../../config")
const post_order = async (instance, is_production, amount, user_data, res) => {
const assemble_data = {
order: {
order_number: user_data.new_id,
reference_number: user_data.new_id,
ordered_at: String(new Date()),
total_sale_price: amount,
taxes: (amount / (100 + user_data.taxes)) * 100,
notes: `${user_data.first_name} ${user_data.last_name}`,
shipping: {
method: user_data.shipping_info.name,
address: {
name: `${user_data.first_name} ${user_data.last_name}`,
company: user_data.company,
phone: user_data.phone,
email: user_data.email,
address: user_data.address_first,
address2: user_data.address_second,
city: user_data.city,
state: user_data.state,
zip: user_data.zip,
country: user_data.country
}
},
billing: {
address: {
name: `${user_data.billing_data.first_name} ${user_data.billing_data.last_name}`,
company: user_data.billing_data.company,
phone: user_data.billing_data.phone,
email: user_data.billing_data.email,
address: user_data.billing_data.address_first,
address2: user_data.billing_data.address_second,
city: user_data.billing_data.city,
state: user_data.billing_data.state,
zip: user_data.billing_data.zip,
country: user_data.billing_data.country
}
},
dealer: null,
items: user_data.products_data
}
}
const axios_instance = await instance
const stringigied_data = JSON.stringify(assemble_data)
try {
const { data } = await axios_instance.post(
`/channels/${ is_production ? API_channel_ID : API_channel_ID_sandbox }/orders`,
stringigied_data
)
res.send({
data: user_data,
order_data: data,
order_id: user_data.new_id
})
} catch(err) {
res.send(err)
console.log(err)
}
}
module.exports = post_order
I have also tried commenting out the items: user_data.products_data to check if it might be causing it, but still the error persist.
I would expect the POST request to go through without a problem.
I think it trying to convert a JSON object that is already a JSON.
I will try to check from here up:
JSON.stringify(assemble_data)

pushing data to embedded array error nodeJS

I'm using mongoose, and I'm getting an error while trying to push some data into an embedded array for one of my already established documents. My app is basically like a forum where a user post a topic question, someone can answer it, and then someone can post a comment on that answer. The problem is that, I've set up my database so that the topics and answers are referenced to one another in separate models, but the comments are embedded within the answer schema. With every method I try I get an error saying either:
message: 'The field \'comment\' must be an array but is of type Object in document {_id: ObjectId(\'5669acad9b68142c1258b472\')}',
driver: true,
index: 0,
code: 16837,
errmsg: 'The field \'comment\' must be an array but is of type Object in document {_id: ObjectId(\'5669acad9b68142c1258b472\')}' }
or:
{ [ValidationError: Answer validation failed]
message: 'Answer validation failed',
name: 'ValidationError',
errors:
{ 'comment.1._id':
{ [CastError: Cast to ObjectID failed for value "[object Object]" at path
"_id"]
message: 'Cast to ObjectID failed for value "[object Object]" at path "_
id"',
name: 'CastError',
kind: 'ObjectID',
value: [Object],
path: '_id',
reason: undefined } } }
Answer.js: model
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var AnswerSchema = new Schema(
{
_topic: {type: Schema.Types.ObjectId, ref: 'Topic'},
_user: {type: Schema.Types.String, ref: 'User'},
likes: Number,
dislikes: Number,
content: String,
created_at: {type: Date, default: new Date},
comment: [{
_user: {type: Schema.Types.String, ref: 'User'},
content: String
}]
});
var Answer = mongoose.model('Answer', AnswerSchema);
topics.js: controller
add_comment: function(req,res)
{
Answer.findOne({_id: req.body.answerid}, function(err, answer)
{
if(err)
{
console.log(err)
}
else
{
console.log(answer);
answer.comment.push([{_user: req.body.currentUser, content: req.body.content}]);
answer.save(function(err)
{
if(err)
{
console.log(err);
}
else
{
res.redirect('/');
}
})
}
})
}
if i simply update the data (to replace other comments) it will process it with no err, if I use an operator like $push I'll receive the same errors.
Thanks for any help.

Categories

Resources