how to create one input text and save the result to separated fields? - node.js

i have a question. how to create one input text and fill it with this format:
, then save the result to database with separated fields:
- name
- age
- address
like example input : "Rangga Lawe 22 Jl Soekarno Jakarta"
so, it will save to database as follows:
- “Rangga Lawe“ to name field
- “22” to age field
- “Jl Soekarno Jakarta” to address field
please help me, thankyou.
im using mongoDb as my database and use node.js framework

Try splitting the value on the basis of some parameters. like instruct the user to input comma separated values. OR
You have to make input field fixed length for each of your values..

if you only have one input means that you have only one string that you want to parse into an array and then insert this fields into your database.
like this:
var str = "Rangga Lawe 22 Jl Soekarno Jakarta";
var result = str.split(" ");
//now you can work with the array
//console.log(result[0]) will contain "Rangga"

You can split the one input into multiple ones at the Schema level if you use Mongoose ORM for your mongoDB database using the .pre middleware.
Here is an example :
UserSchema.pre('save', function(next) {
const user = this
const data = user.fieldYouWantToSplit.split(" ")
user.address = data[0]
user.number = data[1]
return next()
})
})

Related

Bulk Insert records in Postgres using nodejs?

I am trying to do multiple insert row using node-postgres, I want id to be created dynamically and return those ids
Following approach, I am using
const insertArray = [['kunal#test.com',1000,'abcdef'],['kunal1#test.com',1000,'fedkcn']]
let query1 = format(`INSERT INTO users VALUES %L returning id`, insertArray);
const newClient = new Client();
await newClient.connect();
let {rows} = await newClient.query(query1);
I am getting errors as
invalid input syntax for type integer: "kunal#test.com",
how can we skip id?
Tried using CSV option via copyfrom also getting the same issue
const stream = client.query(copyFrom(`COPY users FROM STDIN (format csv, DELIMITER ',', HEADER)`))
const readStream = fs.createReadStream('./tmp/copy.csv');
copy.csv
"email","amount","address"
'kunal#test.com',1000,'abcdef'
USERS table schema
id email amount address
Integer. String. Integer. String.
Not sure how to auto-generate id and return the rows containing new id.
Cannot provide the col name also, as this functionality will also be used by other schemas.
If I provide id it works fine
Thanks for help
Inserting (either by insert or copy) without specifying column names is positional operational in order of column definition. In other words here insert into users values ... is the same as insert into users(id, email, amount, address) values .... However, your data does not have the same structure. The solution is to specify your columns:
... INSERT INTO users(email, amount, address) VALUEs...
... COPY users(email, amount, address) FROM STDIN ...

Get multiple documents from collection using nodejs and mongodb

Hi I have two mongodb collections. The first one returns json data (array) and with the output of this, I want to return documents that match.
When I run Console.log (req.bidder.myBids) I get the following output:
[{"productId":"3798b537-9c7b-4395-9e41-fd0ba39aa984","price":3010},{"productId":"3798b537-9c7b-4395-9e41-fd0ba39aa984","price":3020},{"productId":"4c4bd71c-6664-4d56-b5d3-6428fe1bed19","price":1040},{"productId":"4c4bd71c-6664-4d56-b5d3-6428fe1bed19","price":1050},{"productId":"4c4bd71c-6664-4d56-b5d3-6428fe1bed19","price":1060},{"productId":"4c4bd71c-6664-4d56-b5d3-6428fe1bed19","price":1070},{"productId":"4c4bd71c-6664-4d56-b5d3-6428fe1bed19","price":1090},{"productId":"4c4bd71c-6664-4d56-b5d3-6428fe1bed19","price":1100}]
The productId has duplicates, I want to remove duplicates and then call a routine that finds all the products that match and output as json.
So far I have this code that only outputs one document, but cant figure out how to add the array of productId's and then fetch all corresponding products.
var agencyId = req.body.agencyId;
var productId = req.body.productId;
if (!validate.STRING(agencyId)) {
res.apiError(messages.server.invalid_request);
} else {
dbProduct.find({productId:{$in:['3798b537-9c7b-4395-9e41-fd0ba39aa984','4c4bd71c-6664-4d56-b5d3-6428fe1bed19']}
}).then(dbRes => {
console.log(dbRes);
Updated code and works with hard-wired productId and updated above code. Looking at how to get the array data and transpose replacing the hard-wired productId's
The $in operator is what you want. See the docs here: https://docs.mongodb.com/manual/reference/operator/query/in/

How to generate random ID instead of auto increment in Mongoose

I am creating an app where customers can scan codes, and when scanned, it opens a website which basically redeems that code. The problem is that all these codes have an auto-incremented ID, so the customer could just redeem all possible codes just by increasing the ID number in the url.. Is there a way to generate random uuid's in mongoose instead of the default auto incremented ObjectID?
You can achieve what you are looking for by the below command:
var mongoose = require('mongoose');
var id = mongoose.Types.ObjectId('4edd40c86762e0fb12000003');
where 4edd40c86762e0fb12000003 is the custom ObjectId you desire for.
To generate a completely random non-incrementing string, use the below code.
let randomString = _.times(16, () = (Math.random()*0xF<<0).toString(24)).join('');
var id = mongoose.Types.ObjectId(randomString);
Make sure that you are Inserting/Updating is a valid ObjectId on length 24 and a duplicate of the same ObjectId doesn't exist in another document in the same collection.
To generate a random ObjectId, use the below code.
var mongoose = require('mongoose');
var id = mongoose.Types.ObjectId();
Note: A random ObjectId will be created if you don't pass any value to the parameter
Furthermore, you can insert any custom _id key inside MongoDB of any recognized MongoDB types, as long as its' unique in that collection, it will work.
Example:
db.col.insertMany([{"_id": 1}, {"_id": 2}])
db.col.insertMany([{"_id": "Product1"}, {"_id": "Product2"}])
will work just fine.
Instead of replacing the entire unique ObjectId with a random number, could you append a random number when printing out the code?
For example, parseInt(Math.floor(Math.random()*65536),16) will give you a random 4-character code. Store that as a validator when writing the document to the database, and append it to the ObjectId when generating the scannable token.
When the user scans the code, you can use the first 24 characters to look up the document, then verify that the last 4 characters match the validator. No external libraries required.
If you want to get even fancier, append a check digit or checksum on the code (such as is done with credit card numbers) so that the client side can sometimes determine that a code is invalid without even consulting the database.

mutivalue date field search not working

I have a multivalue field called freeDaysPool which has multiple dates as strings. With the following code, the search does not return anything. If I leave that field out, the search works just fine with the two other fields. I read that I should use CONTAINS with multivalue fields but then I got query not understandable.
I've tried the back-end field as a date field and as a text field and tested all kinds of query combinations and date formats but no luck. Any help is really appreciated.
This is the search button code:
var query = new Array("");
var cTerms = 0;
// Field 1
var search01 = getComponent("searchcustomReservationField01").getValue();
if (#Contains(#Text(search01),"any city")){"";}
else {query[cTerms++] = '[customReservationField01]="' + search01 +'"'};
// Field 2
var search02 = getComponent("searchcustomReservationField02").getValue();
if (#Contains(#Text(search02),"any city")){"";}
else {query[cTerms++] = '[customReservationField02]="' + search02 + '"'};
// Date 1
var formatter = new java.text.SimpleDateFormat("d.M.yyyy");
query[cTerms++] = 'FIELD freeDaysPool = ' + formatter.format(getComponent("searchcustomDateField01").getValue());
// if query is still empty, we fill it with asterisk
if(query == "" || query == null){
query[cTerms++] = "*";
}
// make all as string
qstring = query.join(" AND ").trim();
sessionScope.searchString = qstring;
It will return query as:
[customReservationField01]="Oslo" AND [customReservationField02]="Oslo" AND FIELD freeDaysPool = 6.2.2015
AFAIK date values in formulas (and a query is a formula) have to be noted like
[06.02.2015]
to compare them. Just try to use your formular in the Notes Client to do a fulltext search. If you get results and no errors you found the correct format. That's at least the way I test queries as I'm not able to remind the syntax for years :-D
Thank you for all the help! Seems that Domino keeps the field type as date field even if you change it back to text field (noticed that from the notes FTsearch). I created completely new text field and added the days as strings in dd.MM.yyyy format. I also search them as strings and it works fine.
The changed code bit now looks like this:
// Date 1
var formatter = new java.text.SimpleDateFormat("dd.MM.yyyy");
query[cTerms++] = '[freeDays] CONTAINS "' + formatter.format(getComponent("searchcustomDateField01").getValue())+'"';

Using string in place of property name (LINQ)

I have been able to get the values from tables using linq.
var q=(from app in context.Applicant
where app.ApplicantName=="")
Now what I want is this:
var q=(from app in context.Applicant
where app.stringIhave =="") // so instead of column name I have string which has same name as column.
Is it possible to specify string in Select as this is not sure what I will get in each case, I need different data all the time.
Is it possible to do so?
If no, then I will figure out something else.
Update
I have a GlobalString, which holds the column name of a table.
So when I query that table, I only specify from string which column value I want to get:
var q=(from app in context.Applicants
where app.ID==1013
select GlobalString //which is specifying that I want to get value from which column, as column name is not fixed.
//where GlobalString can have values like: app.FirstName..app.LastName etc
Update1:
var q = context.Applicants.Select("new(it.ApplicantFirstName as FirstName, it.ApplicantLastName as LastName)");
Error Message:
The query syntax is not valid. Near keyword 'AS'
You can use Dynamic Linq (available from NuGet) for that:
var q = context.Applicant.Where(app.stringIhave + " = #0", "");
for select you can try something like this
var q = context.Applicant.Select("new(it.FirstName as FirstName, it.LastName as LastName)");
so you only need construct string for that format

Resources