How to send array POST/GET parameter with node.js - javascript

I want to send a data like this to a rest Webservice :
let params = {
uri: getWsUrl(),
body:queryString.stringify({
city: 885,
customer: user.id,
basket: [
[
product_id: 448025,
count: 2
]
]
})
};
I use request.post(params, function(...)) method for send parameter to Webservice. After sending this request to the server, I get the parameters with $_POST But basket is empty!
Can you help me?

For sending data in response use render, consider the following example
response.end(JSON.stringify({'title': 'Welcome', 'subtitle': "Users List", 'user': result}));

You are trying to send a nested array as if it were an object.
You have two option. Either change the array inside the array to an object.
city: 885,
customer: user.id,
basket: [
{
product_id: 448025,
count: 2
} //HERE
]
}
Or if you really want that array in there (please don't. Try to keep your data as flat as possible.
You can do this (not recommended). Just wrap it in an object
city: 885,
customer: user.id,
basket: [
[{
product_id: 448025,
count: 2
}]
]
}

Related

Add nested collections with aggregation in mongoose?

I'm new to mongoose, I'm confuse while create the query. Can you help me?
I have video collection like this:
{
_id: 603dea86cef0aed372cd9ce6,
category: [
"603dea86cef0aed372cd9cd8", // array of category objectId
"603dea86cef0aed372cd9cd9"
],
hashtag: [
"603dea86cef0aed372cd9cee" // array of hashtag objectId
],
video_id: '6925666264463576320',
share_id: 'greate_video',
author: 603dea86cef0aed372cd9cd8, // ref to Author objectId
cover: 'https://path.to/img.jpg',
post_by: 60083f24edae03650406ad48, // ref to User objectId
status: 1, // enum status [0, 1, 2]
date: 2021-03-02T07:34:30.635Z
}
I want to query to get data with structure like below. I mean, I will find by _id and get related data form other collections, more than that, I want the video list show with status 1, 2 (not 0) and sort by video _id: -1.
{
_id: 603dea86cef0aed372cd9ce6,
category: [
{_id: "603dea86cef0aed372cd9cd8", category_name: Tech},
{_id: "603dea86cef0aed372cd9cd9", category_name: Mobile},
],
hashtag: [
{_id: "603dea86cef0aed372cd9cee", hashtag_name: tech},
],
video_id: '6925666264463576320',
share_id: 'greate_video',
author: {_id: "603dea86cef0aed372cd9cd8", author_name: Nani, avatar: 'https://path.to/avatar.jpg'},
cover: 'https://path.to/img.jpg',
post_by: {_id: "603dea86cef0aed372cd9cd8", user_name: Username, avatar: 'https://path.to/avatar.jpg'},
status: 1,
date: 2021-03-02T07:34:30.635Z
}
How do I write the aggregation query? I tried with query like this but doesn't work, it show empty [] result.
const videoList = await Video.aggregate([
{
$lookup:
{
from: 'Author',
localField: "author",
foreignField: "_id",
as: "author_info"
}
}
])
Thank you
name of collection usually written in plural lowercase letters so I think you should change Author to authors

Map array of objects by ID and update each existing object in the array

I'm trying to make a call, return an array of objects, then loop through each object in the array by the id and make an additional call. With this second fetch, I need to add a new object to each corresponding object within the original array. Please see code samples below and thank you in advance!
Steps:
Pass search params into postSearchPromise
Map over results and store an array of all id's
Pass each id into the getMediaPromise (I've already defined the token)
Add each response object from the getMediaPromise to the corresponding object in the existing array.
Use a reducer to store the final results (This is a React Native app, i'm using a FlatList on the following screen that points to this stored data, looping through the array and displaying the list on screen)
async function search() {
const toSend = {
title,
age,
location
};
try {
const results = await postSearchPromise(token, toSend);
const theUsers = await results.map(getUsers);
function getUsers(item) {
var users = item.id;
return users;
}
const avatars = await getMediaPromise(token, theUsers);
const mapped = await results.map(element => ({avatar: avatars ,...element}));
dispatch({type: 'SEARCH_RESULTS', payload: mapped});
} catch (e) {
console.log("The Error:" , e);
}
}
Currently, this almost works, but "avatar" takes all of the id's from getUsers and sends them in a comma separated list, together at once, inside the "getMediaPromise," - this is not the intent, but I understand why the code is behaving this way. I'm not sure how to loop through each id and add the new object to each existing object in the array.
The search results I start with:
[
{
id: "123",
name: "John",
location: "USA"
},
{
id: "456",
name: "Jane",
location: "USA"
},
{
id: "789",
name: "Jerry",
location: "USA"
}
]
The search results I need to finish with:
[
{
id: "123",
name: "John",
location: "USA",
avatar: {
type: "default",
status: "200",
ok: true,
url: "http://localhost:3000/media/123"
}
},
{
id: "456",
name: "Jane",
location: "USA",
avatar: {
type: "default",
status: "200",
ok: true,
url: "http://localhost:3000/media/456"
}
},
{
id: "789",
name: "Jerry",
location: "USA",
avatar: {
type: "default",
status: "200",
ok: true,
url: "http://localhost:3000/media/789"
}
}
]
I'm open to an entirely different way to do this, but as mentioned above... I'm using a FlatList on the following screen so it's essential that this is a single array of objects so my FlatList can easily loop over the stored data and pull each piece accordingly. Thanks!

Combine two expect statements that perform check on single json response

I'm writing a test to check that a function in my Node.js application which returns this JSON structure:
}
id: 1,
name: 'John Doe',
email: 'j#doe.com',
phone: '+123',
suppliers: [
{
id: 1,
name: 'Supplier1'
}
]
}
I have this expect:
expect(res.body.users[0]).to.be.an.instanceof(Object)
.that.includes.all.keys([
'id',
'name',
'suppliers',
]);
I also want to check there are details in suppliers. I could just add this in another expect:
expect(res.body.users[0].suppliers[0]).to.be.an.instanceof(Object)
.that.includes.all.keys([
'id',
'name',
]);
Is it possible to combine both into one expect statement though?

SEQUELIZE - How to Get All Assosciated Objects?

I have a many to many association like this:
Squad.belongsToMany(Member, {through: Membership});
Member.belongsToMany(Squad, {through: Membership});
How do I find all the Squads, and for each squad, show me the squad name and an array with the Members that each squad has associated with it?
UPDATED WITH WHAT I'VE BEEN TRYING AND WHAT RESULTS I GET:
I've been trying things like this:
Squad.findAll({
include: [{
model: Member,
required: true
}]
}).then(squads => {
// The rest of your logics here...
});
Here's a sample of what I get:
{ id: 3,
name: 'Knicks',
city: 'NYC',
state: 'NY',
'members.id': 3,
'members.name': 'Carmelo',
'members.city': 'NYC'
},
{ id: 3,
name: 'Knicks',
city: 'NYC',
state: 'NY',
'members.id': 2,
'members.name': 'Penny',
'members.city': 'Orlando',
'members.state': 'Florida'
}
But what I want is not multiples of the same object and individual member info. I'm trying to get something more like this:
{
id: 2,
name: 'Lakers',
members: [ memberInfo, memberInfo, memberInfo]
}
Is there a way to do that?
Assuming that you modeled your relations correctly, then you should be able to do something like
Squad.findAll({
include: [{
model: Member,
required: true
}]
}).then(squads => {
// The rest of your logics here...
});

Meteor: group documents and publish an object

I would like to know how to group documents according to a condition, and publish to the client.
Suppose I have the following documents:
[
{ name: 'John', createdAt: some_date_value_1 },
{ name: 'Jane', createdAt: some_date_value_2 },
{ name: 'Bob', createdAt: some_date_value_1 },
{ name: 'Jenny', createdAt: some_date_value_2 }
]
What can I do to publish a result like this?
{
some_date_value_1: [
{ name: 'John', createdAt: some_date_value_1 },
{ name: 'Bob', createdAt: some_date_value_1 }
],
some_date_value_2: [
{ name: 'Jane', createdAt: some_date_value_2 },
{ name: 'Jenny', createdAt: some_date_value_2 }
]
}
Any suggestions?
It depends of you want to do it on client or server.
First, the obvious solution: if you have no specific reason to store them with the first structure, store them directly using the second.
Second, another easy solution is to make in client. Here is a non tested code using undercore (bundled with meteor):
var yourCollection = CollectionName.find();
var yourCollectionByDate = _.groupBy(yourCollection , 'createdAt');
Third, you could still do it on server but either you will loose the reactivity of your collection (using for instance Collection.aggregate with a package) or have to transform and observe all changes afterwards (it would be a little overkill. However have a look here if you want more info)
A quick side note too: unless you want the users names to be unique, you should rely on mongo unique id (_.id) rather than on a name you set. That way, you are sure that you link to the right item (no duplicate).

Categories