How to add continuation backslash or character to MongoDB script - javascript

I need to write a script to create multiple users and roles in MongoDB from the command line..
Below is an example of one of the scripts.
mongo $DB --eval "db.createUser({ user: '$USER', pwd: '$PASS', roles: [ { role: '$ROLE', db: '$DB' } ] });"
I know in bash, you can simple add back slash to condense a lengthy script
mongo $DB --eval \
"db.createUser({ user: '$USER', pwd: '$PASS',\
roles: [ { role: '$ROLE', db: '$DB' } ] });"
I tried the something similar to bash but the script is treating the slash as a literal string. Any idea how to fix the issue?

The problem is with a space character present after the \ character in the second line. The below command will work for you.
mongo $DB --eval \
"db.createUser({ user: '$USER', pwd: '$PASS',\
roles: [ { role: '$ROLE', db: '$DB' } ] });"

Related

Getting strange encodings with nextjs and graphQL when storing in DB

I am storying names in my database from foreign countries which mean a few of the characters are not easily stored in my db for some reason:
Example name that is not stored correctly:
Moretó Font
It is a postgres DB with a graphQL layer on to to get the data out.
DB Info:
psqlDB| TF8 | en_GB.UTF-8 | en_GB.UTF-8 |
I have <meta charSet="utf-8"/> in the page
I'm using:
postgres v12
node.js v14.15.4
nextjs v10
graphql v15.4
postgraphile: v4.5.5
postgraphile generates my schemas and resolves for me so a typical write to my DB looks like within my nextjs application (javascript):
mutation createArtist(
$firstname: String!
$surname: String!
) {
createArtist(
input: {
artist: {
firstname: $firstname
surname: $surname
}
}
) {
clientMutationId
}
}
create({ variables: { firstname: 'jamie', surname: 'hutber'} })
I wonder if I need to remove all these chars while storing them in the DB?

Node JS - Mysql : invisible characters

To simplify, I save a JSON in my Mysql database, the JSON has this form:
{
"idAd": "",
"titleAd": "F2 47m² 1340 CC",
"dateAd": "2017-11-26",
"priseAd": 1340,
}
The field "titleAd" can contain special characters, including some weird and invisible characters :p
So when I make an extraction of this field the invisible character turns into "?"
I know it's a basic and simple encoding problem but I can't find the solution.
{
"idAd": "",
"titleAd": "F2 47m² 1340? CC",
"dateAd": "2017-11-26",
"priseAd": 1340,
}
For information I have specified the type of encoding in connection to the database
const mysql = require('mysql');
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
database: 'dababase',
charset: "utf8_general_ci"
});
Thanks for your help.

Creating multi variable GraphQL query

I've been reading and trying alot of Stuff, but only using cURL as tools. Are there other ways run tests against an GraphQL endpoint?
So my problem is an mutation query with serveral variables. Here is part of my Shema:
type mutation {
oneComponentTypeCollected(userID: String!, password: String!, pageID: Int!,
Components: ComponentsInput!): Page
}
type Components {
ComponentType: ComponentType!
required: Int!
collected: Int!
}
type ComponentsInput {
id: String!
collected: Int!
}
type Page {
id: Int!
}
How do i call query the oneComponentCollected mutation?
What is expected is to set the collected value to 1 of the Component "inkpad_blue"
I tried the Following:
Variable syntax:
{"query":"mutation($input:ComponentsInput!) {oneComponentTypeCollected(userID: \"asd\", password: \"asd\", pageID: 1, input:$input){id}}","variables":{"input":{"id":"Inkpad_blue","collected":1}}}
as pure String:
mutation($input:ComponentsInput!) {oneComponentTypeCollected(userID: "asd", password: "asd", pageID: 1, input:$input){id}}
Both result in 500 HTTP errors.
I think your mutation should go like this
mutation{oneComponentTypeCollected(userID: "asd", password: "asd", pageID: 1, Components:{"id": "Inkpad_blue","collected": 1}){id}}
Try this in your graphiql

Full-Text Search in Node JS with Mongoose

I'm trying to perform a full-text search on an array of strings in Mongoose and I am getting this error:
{ [MongoError: text index required for $text query]
name: 'MongoError',
message: 'text index required for $text query',
waitedMS: 0,
ok: 0,
errmsg: 'text index required for $text query',
code: 27 }
However, I do have a text index declared on the field on the User Schema and I confirmed that the text index has been created because I am using mLab.
I am trying to perform a full-text search on fields
Here Is My User Schema:
var userSchema = mongoose.Schema({
local: {
firstName: String,
lastName: String,
username: String,
password: String,
fields: {type: [String], index: true}
}
});
Here is My Code for the Full-Text Search:
User.find({$text: {$search: search}}, function (err, results) {
if (err) {
console.log(err);
} else {
console.log(results);
}
});
For $text queries to work, MongoDB needs to index the field with a text index. To create this index by mongoose use
fields: {type: [String], text: true}
See here for the MongoDB documentation of text indexes.
You need to add a text index to your schema like below:
userSchema.index({fields: 'text'});
Or use userSchema.index({'$**': 'text'}); if you want to include all string fields
If for some reason adding a test index is not an option, you could also use the regex operator in your aggregation pipeline to match strings.
$regex
Provides regular expression capabilities for pattern matching strings
in queries.
MongoDB uses Perl compatible regular expressions (i.e.
“PCRE” ) version 8.42 with UTF-8 support.
To use $regex, use one of
the following syntaxes:
{ <field>: { $regex: /pattern/, $options: '<options>' } }
{ <field>: { $regex: 'pattern', $options: '<options>' } }
{ <field>: { $regex: /pattern/<options> } }
In MongoDB, you can also use regular expression objects (i.e.
/pattern/) to specify regular expressions:
{ <field>: /pattern/<options> }

Mongoose JS findOne always returns null

I've been fighting with trying to get Mongoose to return data from my local MongoDB instance; I can run the same command in the MongoDB shell and I get results back. I have found a post on stackoverflow that talks about the exact problem I'm having here; I've followed the answers on this post but I still can't seem to get it working. I created a simple project to try and get something simple working and here's the code.
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema({
userId: Number,
email: String,
password: String,
firstName: String,
lastName: String,
addresses: [
{
addressTypeId: Number,
address: String,
address2: String,
city: String,
state: String,
zipCode: String
}
],
website: String,
isEmailConfirmed: { type: Boolean, default: false },
isActive: { type: Boolean, default: true },
isLocked: { type: Boolean, default: false },
roles: [{ roleName: String }],
claims: [{ claimName: String, claimValue: String }]
});
var db = mongoose.connect('mongodb://127.0.0.1:27017/personalweb');
var userModel = mongoose.model('user', userSchema);
userModel.findOne({ email: 'test#test.com' }, function (error, user) {
console.log("Error: " + error);
console.log("User: " + user);
});
And here is the response of the 2 console.log statements:
Error: null
User: null
When the connect method is called I see the connection being made to my Mongo instance but when the findOne command is issued nothing appears to happen. If I run the same command through the MongoDB shell I get the user record returned to me. Is there anything I'm doing wrong?
Thanks in advance.
Mongoose pluralizes the name of the model as it considers this good practice for a "collection" of things to be a pluralized name. This means that what you are currently looking for in code it a collection called "users" and not "user" as you might expect.
You can override this default behavior by specifying the specific name for the collection you want in the model definition:
var userModel = mongoose.model('user', userSchema, 'user');
The third argument there is the collection name to be used rather than what will be determined based on the model name.
I know 7 years pass, however I'm starting to develop in node JS with MongoDB using mongoose, so searching for solution to the same problem, result = null.
After read this post and all the answers, I release that I totally forget to include the DB name in the string of the connection, 'mongodb://localhost:27017/DB name' so that solved my case. I guessed this can be help other clueless like me! :)

Categories