var db = mongoose.connection;
const FoundWarning = db.collection('warning').find({UserID: Warned.user.id, guildID: message.guild.id}).toArray(function(err, results) {
console.log(results);
})
I was trying to find more than one collection using MongoDB,
I don't quite know how to map it and turn it into a String as there are multiple responses and not just one JSON document to use so I would have to map through them,
Can someone explain how I can turn this Data to chunks that I can use like a string, an object or an array?
I suppose I have to parse it and map it first, correct me if I'm wrong
But I don't think I know how to do that
Here is the photo of the current result that I have
I wanted to (for example) get the "Reason" part of it in a string alone and send each "Reason" along side with the "UserName" and send it as a message on discord using discord.js so like loop through them for example
Edit: i forgot to mention that "Warned" is
let Warned = message.mentions.members.first();
Sorry if I'm not good at explaining, I would appreciate edits if you understand what's the issue that I'm facing
Like I said here
You can simply access the Reason property of an object. What you are facing is an array of objects and each object inside the array contains a Reason property. You can either access one object, for example, results[0] and then access the Reason property like this results[0].Reason or you can store all the reasons inside an array like this:
const reasons = results.map(result => result.Reason);
Related
Normally what we do is like
const hash = new Map()
hash.set(key,value)
And when we want to retrieve the information just
hash.get(specificKey)
One of the benefits that Map has is that we can put whatever we want as key or value.
I'm trying to set a multiple value of keys on the "key" part of the map, that's not the problem is later when I want to get the information
Example:
[
{name:"Pedro",email:"test1#gmail.com"},
{name:"Anibal",email:"test2#gmail.com"},
]
I want to create the key of the map with both properties of the object (name, email), and the value is ALL the iterated register so...
const hash = new Map()
for (register of registers) {
const { name, email } = register
hash.set([name, email], register)
}
The problem is when I want to GET the register by one of the properties on the key.
We know that the key could be ["Pedro","test1#gmail.com]
How I can get the value of the Map if the key I want to get could be just "Pedro" or just "test1#gmail.com"
It is possible? :(
Thank you
___________________-
Answer to #Kevin Kinney
Thank you for answering. The idea that I want to do is to avoid this;
I dont want to have a find inside the map. Any different approach?
One idea, if you know only a few of the properties would be used as keys
const hash = new Map()
for (register of registers) {
const { name, email } = register
hash.set(name, register)
hash.set(email, register)
}
This will allow fast access to the value in the map, but increases the memory usage.
Otherwise I don't think a hashmap is the right idea if you don't know what key you will be expecting to use.
No, this is not possible
You want access in a non-standard way so what you can do is create two mappings for each value. One goes from pedro and one goes from test1#gmail.com
Then when you need to retrieve the value you can get it by either
So I'm working on a personal project to learn react-native and Firestore.
I have a DB like this:
And I want my code to add a new battery in the array batteries.
The elements in the array are just a map{string, string}
The problem is that when I update the array with a new brand that's work but if I want to update it with the same brand again have,
so having by the end
batteries[0]: {'brand': 'cestmoi'}
batteries[1]: {'brand': 'cestmoi'}
The DB doesn't update, doesn't have any error or so.
I don't understand why and I followed their tutorial. Here is my code:
async function addData(collection, doc, value) {
console.log(`Add data ${value.brand}`)
try {
const result = await firestore()
.collection(collection)
.doc(doc)
.set({
batteries: firestore.FieldValue.arrayUnion(value)
})
console.log(result);
return result;
} catch (error) {
return error;
}
}
I use try-catch by habit but I don't know if the then...catch is better or not.
As already #windowsill mentioned in his answer, there is no way you can add duplicate elements in an array using client-side code. If your application requires that, then you have to read the entire array, add the duplicates and then write the document back to Firestore.
However, if you want to update an existing element in an array of objects (maps) then you have to use arrayUnion with the entire object. If you want to understand the mechanism better, you can read the following article which is called:
How to update an array of objects in Firestore?
arrayUnion says that it "adds elements to an array but only elements not already present". Maybe it does a stringify or something to check equality and therefore doesn't add the new element. I think you'll have to 1. get the current list, 2. add your element, 3. set the batteries field to the updated list.
I have problem with Mongo/express array parsing. A array from body seems to be correct when I console.log response in node console. But the problem is when I try to save the body to mongo.db using insert.one method, the post is saved but the array turns into string, which is bad for me.
This is what I'm sending to mongo (the data is ok, i console.log it, array is not string here)
{
createdBy: this.userName,
postContent: this.post,
tags: this.tags,
addedAt: new Date()
};
And this is what is stored in database
Update:
When I hardcode array into payload it's showed correctly as an array in mongo.
But of course problem still exist for dynamic data
You should be able to use JSON parse along with a replace to force it to accept the string as an array, like this:
const array = JSON.parse(this.tags.replace(/'/g, '"'));
Then set tags to the value of array:
tags: array
Use data type as array -- 4 and use .pretty().
Generally if you use find() method returns data in a dense format.
By using cursor.pretty() you can set the cursor to return data in a format that is easier for humans to parse
I'm working with Node.js and MongoDB, I used this line:db.collection('users').insertOne({"name":"john", "password":"connor"}) to insert a new document, and now I'd like to get the password from it.
I tried with: var users_array = db.collection('users').find({name:"john"},{password:true, _id:false}).toArray() and I get an array that looks like this: [{"password":"connor"}]
Any way to get that value and save it in a string or something similar?
There is nothing special about the array returned. You access properties the same way you always do in JavaScript:
var password = result[0].password;
If you use findOne instead of find you will just get the object directly, without the array, so then you can just use:
var password = result.password;
Side note: You should never store passwords in a way where someone (including yourself) could look inside the database and figure out a password. That means no plaintext and no encrypted passwords. They should be hashed with a random salt, and not by a fast hashing algorithm. Use pbkdf2 or bcrypt.
I'm using an API which returns an array of results, let's call them "employees" and let's say it returns "employee.id" and "employee.name".
I know the "age" of each employee and I have it in a list (JSON file).
What I'm trying to achieve is: whenever a user makes a search, the app will pull results from "employees", match all the id's from "employees" to id's in my JSON file, and returns an array with "employee.id", "employee.name" and "employee.age".
Or at least that's the theory.
What is the best practice? Should the app search the API and then my JSON or both at the same time? How do I "match" the two?
I don't think the language really matters here, but I'm writing it in Node.js
Because you've provided no specifics about the API or JSON file, an answer can't be made very specific either so here's a general concept.
Use an async file access method in node.js, read the JSON file into memory and when it loads, parse it into a Javascript array.
As soon as you start the async file read, then start your API call.
When both async operations have finished (I personally would use Bluebird in nodejs to promisify both operations so they each returned a promise and would then use Promise.all() to know when both async operations were done.
Then, get the employee.id from the API call and do a search for that id in the array of employees that came from the JSON file. If you only have to do this once, you can do a brute force search through the array (just looping through the array and comparing each object in the array to see if the id matches).
Once you find the matching id in the array, you can then get the age and name from that same object and you should now have all the info you want.
If this is a common operation, then you probably want to load the JSON file just once, save it persistently in your nodejs application and you may also want to create an index by id so you can just do a direct lookup on the id rather than having to do a brute force search each time.
A brute force search of an array of objects for a particular .id property could look like this:
function findEmployeeById(id) {
for (var i = 0; i < employeeData.length; i++) {
if (employeeData[i].id === id) {
return employeeData[i];
}
}
return null;
}