Replace every name in a file by its google translation - javascript

I have a stations.js file that look like that :
module.exports = [
{
name: 'センター',
assetID: '01101010',
latitude: 43.062222,
longitude: 141.354167,
mongoID: 'b822dff1e50760b99248',
},
{
name: '北1条',
assetID: '01101520',
latitude: 43.062222,
longitude: 141.353889,
mongoID: '493062f76e253bd5cbe6',
},
...
]
I want to replace all the japanase names by their english translation from Google API (I haven't work on that yet for now let's say I want to replace them by a random work like "hello").
For example I want to rewrite my file like so :
module.exports = [
{
name: 'hello',
assetID: '01101010',
latitude: 43.062222,
longitude: 141.354167,
mongoID: 'b822dff1e50760b99248',
},
{
name: 'hello',
assetID: '01101520',
latitude: 43.062222,
longitude: 141.353889,
mongoID: '493062f76e253bd5cbe6',
},
...
]
That's the first time I do something like that and I'm pretty lost. For now my code looks like that :
const fs = require('fs');
function runScript() {
fs.readFile(process.argv[2], 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
fs.readFile(process.argv[3], 'utf8', function (err,logs) {
if (err) {
return console.log(err);
}
const newSta = {}
const rawNewSta = logs.match(/\s*name:\s*'(.*?)'/g)
rawNewSta.map(id => ({
name: id.split(`'`)[1],
})).forEach(station => newSta[station.name] = "hello")
console.log(newSta)
const splitFile = data.split(Object.keys(newSta))
let body = splitFile.reduce((acc, val) => `${acc}${val}name: '${readName(val, newSta)}',`, '')
body += splitFile.splice(-1)
// console.log("->", body)
fs.writeFile('stationsNew.js', body, function (err) {
if (err) return console.log(err);
console.log('stationNew.js created');
});
})
})
}
function readName(stationStr, newSta) {
const station = stationStr.match(/name:\s*['"](.*)['"],/g)
const name = station.splice(-1)[0].split(/name:\s*['"]/)[1].split(/['"],/)[0]
return newSta[name] ? newSta[name] : ''
}

You have an array of objects, so you can just work with it as an array of objects instead of doing all this string manipulation you're trying.
// in real life use `import` here
module = {}
module.exports = [
{
name: 'センター',
assetID: '01101010',
latitude: 43.062222,
longitude: 141.354167,
mongoID: 'b822dff1e50760b99248',
},
{
name: '北1条',
assetID: '01101520',
latitude: 43.062222,
longitude: 141.353889,
mongoID: '493062f76e253bd5cbe6',
}
]
for (item of module.exports) {
item.name = "hello" // or go get the translation here and substitute it in
}
console.log(module.exports) // in real life use fs.writeFile()

Related

How to search nested property in mongoose

hi I have mongodb document like below:
{
_id: ObjectId("63df40c651f1358f2b60f24a"),
origin: {
country: 'Usa',
state: 'Washington',
city: 'Washington',
type: 'Point',
coordinates: [ 12.555, 18.645 ]
},
destination: {
country: 'Usa',
state: 'Montana',
city: 'Yellowstone',
type: 'Point',
coordinates: [ 12.555, 20.645 ]
},
date: 'mon 2023-12-16',
seats: 4,
status: 'pending',
driver: {
firstName: 'sam',
lastName: 'johnson',
phoneNumber: '92823831736',
socialNumber: '1381222327',
driverId: '63d8f94202653dc3592a0aa4'
},
I use below url and code for finding location base on destination:
URL: "localhost:3000/api/v1/travel/?state=Montana&city=Yellowstone"
and my code is:
const Travel = require("../models/travel-model");
const getAllTravelsByDestination = async (req, res) => {
const { country, state, city } = req.query;
const queryObject = {};
if (country) {
queryObject.destination.country = country;
}
if (state) {
queryObject.destination.state= state;
}
if (city) {
queryObject.destination.city = city;
}
const travelList = await Travel.find({ destination:queryObject });
res.status(StatusCodes.OK).json({ status: "success", travelList });
};
I expect to get my document back but instead i get empty list as response:
{
"status": "success",
"travelList": []
}
please help me for this problam
You created a filter properly. But, instead of find({ destination: queryObject }), you should only do find(queryObject), since the queryObject already contains the destination property.
const travelList = await Travel.find(queryObject);
Check this line of your code:
const travelList = await Travel.find({ destination:queryObject });
You defined destination already in the queryObject. So you should just do
await Travel.find(queryObject);
Please note that queries are by default case-sensitive. So upper & lowercase matters.

How can I $push an item in two different fields, depending on the condition?

I'm trying to receive the user location and store it in the database. Also, the user can choose if he wants to save all his previous locations or not.
So I have created a boolean variable historicEnable: true/false.
So when the historicEnable is true, I want to push to historicLocation[] array in the UserSchema and if it is false, I want just to update currentLocation[] array in the UserSchema.
conntrollers/auth.js
exports.addLocation = asyncHandler(async (req, res, next) => {
const {phone, location, status, historicEnable} = req.body;
let theLocation;
if (historicEnable== true){
theLocation = await User.findOneAndUpdate(
{ phone },
{ $push:{ locationHistoric: location, statusHistoric: status }},
{ new: true }
)
} else if(historicEnable== false){
theLocation = await User.findOneAndUpdate(
{ phone },
{ location, status },
{ new: true }
)
}
res.status(200).json({
success: true,
msg: "A location as been created",
data: theLocation,
locationHistory: locationHistory
})
})
models/User.js
...
currentLocation: [
{
location: {
latitude: {type:Number},
longitude: {type:Number},
},
status: {
type: String
},
createdAt: {
type: Date,
default: Date.now,
}
}
],
historicLocation: [
{
locationHistoric: {
latitude: {type:Number},
longitude: {type:Number},
},
statusHistoric: {
type: String
},
createdAt: {
type: Date,
default: Date.now,
}
}
]
Also, not sure how to make the request body so the function works.
req.body
{
"phone": "+1234",
"historicEnable": true,
"loications": [
{
"location": {
"latitude": 25,
"longitude": 35
},
"status": "safe"
}
]
}
To sum up, if historicEnable is true, the data will be pushed in historicLocation, and if it false, to update the currentLocation.
How can I solve this?
You can use an update with an aggregation pipeline. If the historicEnable is known only on db level:
db.collection.update(
{phone: "+1234"},
[
{$addFields: {
location: [{location: {latitude: 25, longitude: 35}, status: "safe"}]
}
},
{
$set: {
historicLocation: {
$cond: [
{$eq: ["$historicEnable", true]},
{$concatArrays: ["$historicLocation", "$location"]},
"$historicLocation"
]
},
currentLocation: {
$cond: [
{$eq: ["$currentLocation", false]},
{$concatArrays: ["$currentLocation", "$location"]},
"$currentLocation"
]
}
}
},
{
$unset: "location"
}
])
See how it works on the playground example
If historicEnable is known from the input, you can do something like:
exports.addLocation = asyncHandler(async (req, res, next) => {
const phone = req.body.phone
const historicEnable= req.body.historicEnable
const locObj = req.body.location.locationHistoric[0];
locObj.createdAt = req.body.createdAt
const updateQuery = historicEnable ? { $push:{ locationHistoric: locObj}} : { $push:{ currentLocation: locObj}};
const theLocation = await User.findOneAndUpdate(
{ phone },
updateQuery,
{ new: true }
)
res.status(200).json({
success: true,
msg: "A location as been created",
data: theLocation,
locationHistory: locationHistory
})
})

Javascript - transforming an object of array list to new formated one?

I'm trying to transform an object contain array to another one with javascript. Below is an example of the object field and what the formatted one should look like.
let Fields = {
GAME: [
{ code: '{{PES}}', title: { en: "playPES"} },
{ code: '{{FIFA}}', title: { en: "playFIFA " } },
]
};
I need The new Fields to looks like this
let newFields = {
name: 'GAME',
tags:[
{ name: 'playPES', value: "{{PES}}" },
{ name: 'playFIFA', value: "{{FIFA}}" }
]},
One contributor suggested me a method like this but i think something need to modify in it but couldn't figure it out.
export const transform = (fields) => ({
tags: Object .entries (fields) .map (([name, innerFields]) => ({
name,
tags: innerFields.map(({code, title: title: {en})=>({name: en, value: code}))
}))
});
// newFields= transform(Fields)
I'm new working with javascript so any help is greatly appreciated, Thanks.
const transform = (o) => {
return Object.entries(o).map((e)=>({
name: e[0],
tags: e[1].map((k)=>({name: (k.title)?k.title.en:undefined, value: k.code}))
}))[0]
}
console.log(transform({
GAME: [
{ code: '{{PES}}', title: { en: "playPES"} },
{ code: '{{FIFA}}', title: { en: "playFIFA " } },
]
}))
Using the entries method you posted:
let Fields = {
GAME: [
{ code: '{{PES}}', title: { en: "playPES"} },
{ code: '{{FIFA}}', title: { en: "playFIFA " } },
]
};
// 1. Obtain keys and values from first object
Fields = Object.entries(oldFields);
// 2. Create new object
const newFields = {};
// 3. Create the name key value pair from new Fields array
newFields.name = Fields[0][0];
// 4. Create the tags key value pair by mapping the subarray in the new Fields array
newFields.tags = Fields[0][1].map(entry => ({ name: entry.title.en, value: entry.code }));
Object.entries(Fields) will return this:
[
"GAME",
[TagsArray]
]
And Object.entries(Fields).map will be mapping this values.
The first map, will receive only GAME, and not an array.
Change the code to something like this:
export const transform = (Fields) => {
const [name, tags] = Object.entries(Fields);
return {
name,
tags: tags.map(({ code, title }) => ({
name: title.en,
value: code
}))
}
}
Hope it help :)
let Fields = {
GAME: [
{ code: '{{PES}}', title: { en: "playPES"} },
{ code: '{{FIFA}}', title: { en: "playFIFA " } },
]
};
let newFields = {
name: 'GAME',
tags:[
{ name: 'playPES', value: "{{PES}}" },
{ name: 'playFIFA', value: "{{FIFA}}" }
]
}
let answer = {
name: "Game",
tags: [
]
}
Fields.GAME.map(i => {
var JSON = {
"name": i.title.en,
"value": i.code
}
answer.tags.push(JSON);
});
console.log(answer);
I think that this is more readable, but not easier... If you want the result as object you need to use reduce, because when you do this
Object.keys(Fields)
Your object transform to array, but reduce can change array to object back.
let Fields = {
GAME: [
{ code: '{{PES}}', title: { en: "playPES"} },
{ code: '{{FIFA}}', title: { en: "playFIFA " } },
]
};
const result = Object.keys(Fields).reduce((acc, rec) => {
return {
name: rec,
tags: Fields[rec].map(el => {
return {
name: el.title.en,
value: el.code
}
})
}
}, {})
console.log(result)
let Fields = {
GAME: [
{ code: '{{PES}}', title: { en: "playPES"} },
{ code: '{{FIFA}}', title: { en: "playFIFA " } },
]
};
const transform = (fields) => ({
tags: Object .entries (fields) .map (([name, innerFields]) => ({
name,
tags: innerFields.map(({code, title: title,en})=>({name: title.en, value: code}))
}))
});
//check required output in console
console.log(transform(Fields));

DynamoDB: Appending an element to a list using Node.js

This doesn't work. Is there another way to do this? cord is a list to which I want to add a map.
var params5 = {
TableName: 'rides',
Key: {
'rid': data2.Items[0].rid
},
UpdateExpression: 'add cord :x',
ExpressionAttributeValues: {
':x': [{date: secondStartDate.toString(), latitude: xcorpassed, longitude: ycorpassed}]
},
ReturnValues: 'UPDATED_NEW'
}
docClient.update(params5, function (err5, data5) { ... }
Instead of ADD, you could use SET with the list_append function (in general, AWS recommends using SET rather than ADD):
(NOTE: The list_append function name is case-sensitive)
var params = {
TableName: "rides",
Key: {
"rid": data2.Items[0].rid
},
UpdateExpression: "SET #c = list_append(#c, :vals)",
ExpressionAttributeNames: {
"#c": "cord"
},
ExpressionAttributeValues: {
":vals": [{date: secondStartDate.toString(), latitude: xcorpassed, longitude: ycorpassed}]
},
ReturnValues: "UPDATED_NEW"
}
docClient.update(params, function (err, data) {
if (err) console.log(err);
else console.log(data);
}
Without seeing the error code it throws it looks like you should change add to set and don't forget the = sign.
var params5 = {
TableName: 'rides',
Key: {
'rid': data2.Items[0].rid
},
UpdateExpression: 'set cord = :x',
ExpressionAttributeValues: {
':x': [{date: secondStartDate.toString(), latitude: xcorpassed, longitude: ycorpassed}]
},
ReturnValues: 'UPDATED_NEW'
}
docClient.update(params5, function (err5, data5) {

Javascript variable scope when mongoose query

I'm working with node.js, mongoose and foursquare API.
foursquare.getVenues(params, function(err, venues) {
if(err) return res.json(JSON.stringify({status: 'error', returnData: err}));
// variable initialization
var rooms = [];
var vanueItem;
// iterate foursquare return list (venue item)
venues.response.venues.forEach(function(item) {
Room.aggregate(
[
{ "$group": {
"_id": '$mobileUser.genderType',
"genderTypeCount": { "$sum": 1 }
}}
],
function(err,result) {
if(err) return res.json(JSON.stringify({status: 'error', returnData: err}));
// build it to return after
vanueItem =
{
id: item.id,
name: item.name,
description: item.description,
contact: item.contact.formattedPhone,
lat: item.location.lat,
lng: item.location.lng,
distance: item.location.distance,
city: item.location.city
};
// insert it into venue array
rooms.push(vanueItem);
}
);
});
return res.json(JSON.stringify({ status: 'success', returnData: rooms }));
});
I'm having a problem with rooms array. When I remove the 'Room.aggregate' query, works fine (all rooms was ok), but when I use the aggregate, the return function gives me empty room.
I already tried remove var from 'var rooms = [];'
Room.aggregate is asynchronous function, if you want iterate over asynchronous function you can use async library, like this
var async = require('async');
foursquare.getVenues(params, function(err, venues) {
if (err) return res.json(JSON.stringify({
status: 'error',
returnData: err
}));
var rooms = [];
var vanueItem;
async.each(venues.response.venues, function (item, next) {
Room.aggregate(
[{
"$group": {
"_id": '$mobileUser.genderType',
"genderTypeCount": {
"$sum": 1
}
}
}],
function(err, result) {
if (err) {
return next(err);
}
// build it to return after
vanueItem = {
id: item.id,
name: item.name,
description: item.description,
contact: item.contact.formattedPhone,
lat: item.location.lat,
lng: item.location.lng,
distance: item.location.distance,
city: item.location.city
};
rooms.push(vanueItem);
next(null);
}
);
}, function (err) {
if (err) {
return res.json(JSON.stringify({
status: 'error',
returnData: err
}));
}
return res.json(JSON.stringify({
status: 'success',
returnData: rooms
}));
});
});

Categories

Resources