I have the following array in my javascript code:
const users = [
{
id: 1,
email: 'test#user.com',
password: 'password',
access_token: 'test_user_access_token'
},
{
id: 2,
email: 'second#user.com',
password: 'password',
access_token: 'second_user_access_token'
}
]
From this collection I want to retrieve user by email. So for example I will write:
my_function("test#user.com") it will return this one user. How can I do this?
You can use Array#find function. Pass a predicate into the function, which will return the first matched item based on that predicate.
const users = [
{
id: 1,
email: 'test#user.com',
password: 'password',
access_token: 'test_user_access_token'
},
{
id: 2,
email: 'second#user.com',
password: 'password',
access_token: 'second_user_access_token'
}
]
function findByEmail(email) {
return users.find(x => x.email === email);
}
console.log(findByEmail('test#user.com'));
That's what the .find() method is for.
const users = [
{
id: 1,
email: 'test#user.com',
password: 'password',
access_token: 'test_user_access_token'
},
{
id: 2,
email: 'second#user.com',
password: 'password',
access_token: 'second_user_access_token'
}
];
console.log(users.find(u => u.email == 'test#user.com'));
So .find() is called on the array, and receives a callback function. The callback will be invoked for each item in the array, for which you return the result of comparing the .email property to the email you're looking for.
As soon as your callback returns a true (or truthy) result, the iteration halts, and returns that object from .find(). If no is found, .find() returns undefined.
Note that this uses arrow function syntax. If you prefer, you can use traditional functions.
console.log(users.find(function(u) { return u.email == 'test#user.com' }));
There's always the good old fashioned for-loop:
const users = [{
id: 1,
email: 'test#user.com',
password: 'password',
access_token: 'test_user_access_token'
},
{
id: 2,
email: 'second#user.com',
password: 'password',
access_token: 'second_user_access_token'
}
]
function findUserByEmail(userList, desiredEmailAddress) {
for (let i = 0; i < userList.length; i++) {
var user = userList[i];
if (user.email === desiredEmailAddress) {
return user;
}
}
return null;
}
var desiredUser = findUserByEmail(users, 'second#user.com');
if (desiredUser) {
console.log('User found by email:\n');
console.log(desiredUser);
} else {
console.log('No user found with searched email address');
}
Related
I have Mongoose CastError issue. I made a nodeJs API. At the specific route, it returns data appended with some other data. I saw many fixes available here but my scenario is different.
Here is my model and the problem occurs at fields property.
const deviceSchema = new Schema({
device_id: { type: String, required: true },
user_id: { type: Schema.Types.ObjectId, ref: 'User', require: true },
location_latitude: { type: String, default: '0' },
location_longitude: { type: String, default: '0' },
fields: [{ type: String }],
field_id: { type: Schema.Types.ObjectId, ref: 'Field', required: true },
timestamp: {
type: Date,
default: Date.now,
},
});
and my controller is
exports.getAllDevices = async (req, res) => {
try {
let devices = await Device.find({})
.sort({
timestamp: 'desc',
})
.populate('user_id', ['name']);
// Let us get the last value of each field
for (let i = 0; i < devices.length; i++) {
for (let j = 0; j < devices[i].fields.length; j++) {
if (devices[i].fields[j] !== null && devices[i].fields[j] !== '') {
await influx
.query(
`select last(${devices[i].fields[j]}), ${devices[i].fields[j]} from mqtt_consumer where topic = '${devices[i].device_id}'`
)
.then((results) => {
************** Problem occurs here **************
if (results.length > 0) {
devices[i].fields[j] = {
name: devices[i].fields[j],
last: results[0].last,
};
} else {
devices[i].fields[j] = {
name: devices[i].fields[j],
last: 0,
};
}
************** Problem occurs here **************
});
}
}
}
// Return the results
res.status(200).json({
status: 'Success',
length: devices.length,
data: devices,
});
} catch (err) {
console.log(err);
res.status(500).json({
error: err,
});
}
};
It actually gets data from InfluxDB and appends it to fields property which was fetched from MongoDB as mentioned in my model. But it refused to append and CastError occurs.
After addition, it will look like this
I can't resolve this error after trying so many fixes. I don't know where I'm wrong. Please suggest to me some solution for this.
I can see you are not using devices variable as Mongoose Document. devices is an array of Documents.
I would like to suggest you to use lean() function to convert from Document to plain JavaScript object like
let devices = await Device.find({})
.sort({
timestamp: 'desc',
})
.populate('user_id', ['name'])
.lean();
This question already has answers here:
Function with forEach returns undefined even with return statement
(5 answers)
Closed 2 years ago.
database = [
{
username: 'mutho',
password: 'muth',
},
{
username: 'pica',
password: '1234',
},
{
username: 'rudy',
password: '1235'
}
];
news = [
{
username: 'sarah',
timeline: 'Hellow',
},
{
username: 'ingrid',
timeline: 'hello world'
},
{
username: 'rudy',
timeline: 'secret',
}
];
function isvalid(user, pass) {
database.forEach(function (item, index) {
if (item.username === user && item.password === pass) {
return true;
}
return false;
});
}
function signIn(user, pass) {
if (isvalid(user, pass) === true) {
console.log(news);
}
else {
alert("Your Username and password wrong");
}
}
var userprompt = prompt("Input your username : ");
var passprompt = prompt("Input your password : ");
signIn(userprompt, passprompt)
I have some problem, I want to show news is the user and password are right in the database. but when I run this program, it always showing "Your Username and password wrong". what should I do?
thank you for the helping
You need Array#some and return the result of this method.
function isvalid(user, pass) {
return database.some(function(item, index) {
return item.username === user && item.password === pass;
});
}
function signIn(user, pass) {
if (isvalid(user, pass)) {
console.log(news);
} else {
alert("Your Username and password wrong");
}
}
var database = [{ username: 'mutho', password: 'muth' }, { username: 'pica', password: '1234' }, { username: 'rudy', password: '1235' }],
news = [{ username: 'sarah', timeline: 'Hellow' }, { username: 'ingrid', timeline: 'hello world' }, { username: 'rudy', timeline: 'secret' }],
userprompt = prompt("Input your username:"),
passprompt = prompt("Input your password:");
signIn(userprompt, passprompt);
Maybe you re looking for something like this:
function findValidUsers(user, pass) {
return database.filter(item => item.username === user && item.password === pass)
}
where findValidUsers will return a array of all users in your database array that have the same username and password.
e.g:
findValidUser('mutho','muth')
would return {username: 'mutho', password: 'muth'}
Your return true does NOT break your loop, it just ends your callback.
See this: Short circuit Array.forEach like calling break.
Or that: https://stackoverflow.com/a/6260865/3872061.
It might help you understand where your problem lies.
foreach doesn't return any value (or break and early return).
Use a standard for loop.
Example https://stackoverflow.com/a/35450142/3327009
Also, the way you have done it now it will just check your first object in the array (if you translate to a for loop)
You need something like this
var i
for (i=0; i<database.length;i++)
if(foobar)
return true
return false
const root = {
user: (id) => {
console.log("returning object " + JSON.stringify(id.id) + " " + JSON.stringify(storage.select("users", id.id)))
return storage.select("users", id.id)
}
}
I want to call the arrow function in root.user but I think I can't pass the parameter correctly, so I tried this --> let user = root.user('101')
and on the console I got this -->
returning object undefined
[{"firstName":"Gokhan","lastName":"Coskun","login":"gcoskun","id":101}]
{"firstName":"George","lastName":"Clooney","login":"gclooney"}
[{"firstName":"Gokhan","lastName":"Coskun","login":"gcoskun","id":101}]
I wanted the user with the id 101 get returned and got instead all of the users returned.
Why are you doing id.id but passing a string? You either pass an object with an id prop (root.user({ id: '101' })) or replace id.id with simply id.
Also, it looks like the id fields in your user objects are of type number, while you are passing a string, so depending on the logic inside storage.select you might have to change that.
Passing a number id:
// Just mocking it for the example:
const storage = {
select(key, id) {
return [
{ firstName: 'Gokhan', lastName: 'Coskun', login: 'gcoskun', id: 101 },
{ firstName: 'George', lastName: 'Clooney', login: 'gclooney' },
{ firstName: 'Gokhan', lastName: 'Coskun', login: 'gcoskun', id: 101 },
// Depending on the logic here, these types need to match.
// Using == instead of === so that it's not required here.
].filter(user => user.id == id)
},
};
const root = {
user: (id) => {
console.log(`ID = ${ id }`);
// We make sure we only return a single user or null if there isn't one:
return storage.select('users', id)[0] || null;
},
};
const user = root.user('101');
console.log(user);
Passing an object with an id prop of type number:
// Just mocking it for the example:
const storage = {
select(key, id) {
return [
{ firstName: 'Gokhan', lastName: 'Coskun', login: 'gcoskun', id: 101 },
{ firstName: 'George', lastName: 'Clooney', login: 'gclooney' },
{ firstName: 'Gokhan', lastName: 'Coskun', login: 'gcoskun', id: 101 },
// Depending on the logic here, these types need to match.
// Using == instead of === so that it's not required here.
].filter(user => user.id == id);
},
};
const root = {
user: (query) => {
console.log(`ID = ${ query.id }`);
// We make sure we only return a single user or null if there isn't one:
return storage.select('users', query.id)[0] || null;
},
};
const user = root.user({ id: '101' });
console.log(user);
The project is created with nodejs and mongoose. What I am trying to do is to update the existing model with addition data (which is a comment, in that case).
This is the model and its methods:
const bugSchema = new Schema({
title: {
type: String,
required: true
},
description: {
type: String,
required: true
},
date: {
type: String,
required: true
},
time: {
type: String,
required: true
},
assignedTo: {
type: String,
required: true
},
assignedBy: {
type: String,
required: true
},
status: {
type: String,
required: true
},
priority: {
type: String,
required: true
},
comments: {
comment:[
{
user:{
type: String,
required: true
},
content: {
type: String,
required: true
}
}
]
}
});
bugSchema.methods.addComment = function(comment){
const username = comment.user;
const content = comment.content;
console.log(comment);
const updatedComments = [...this.comments];
updatedComments.push({
user : username,
content: content
});
this.comments = updatedComments;
return this.save();
};
The controller, which is passing the information from the form:
exports.postComment = (req,res,next) =>{
const bugId = req.body.bugID;
const name = req.session.user.fullName;
const content = req.body.content;
const prod = {name, content};
Bug.findById(bugId).then(bug =>{
return bug.addComment(prod);
})
.then(result =>{
console.log(result);
});
};
I am getting a following error:
(node:3508) UnhandledPromiseRejectionWarning: TypeError: this.comments is not iterable
(node:3508) UnhandledPromiseRejectionWarning: TypeError: this.comments is not iterable
The error indicate you're trying to iterable a type of data which does NOT has that capability.
You can check that printing the type:
console.log(typeof this.comments)
Or even, priting the whole object:
console.log(this.comments)
as you can see, in both cases you're getting an object, not a list (how you spect)
So you can do 2 things:
1- Iterable a list
this.comments is an object but into that object you have the list you want, so just use the list instead.
bugSchema.methods.addComment = function(comment){
const username = comment.user;
const content = comment.content;
console.log(comment);
//const updatedComments = [...this.comments];
const updatedComments = [...this.comments.comment];
updatedComments.push({
user : username,
content: content
});
this.comments = updatedComments;
return this.save();
};
Or you can modify your schema making the comments a list instead of an object
2- comments as list in schema
Define the comments attribute as a list
const bugSchema = new Schema({
title: {
type: String,
required: true
},
description: {
type: String,
required: true
},
...
...,
comments:[
{
user:{
type: String,
required: true
},
content: {
type: String,
required: true
}
}
]
});
And then, try to iterable it as how you been doing
bugSchema.methods.addComment = function(comment){
const username = comment.user;
const content = comment.content;
console.log(comment);
const updatedComments = [...this.comments];
updatedComments.push({
user : username,
content: content
});
this.comments = updatedComments;
return this.save();
};
I am not sure but comments is an object and not an array so you can't push using [...this.comments] and I think it is the comment you want to push?
const updatedComments = [...this.comment];
updatedComments.push({
user : username,
content: content
});
this.comment = updatedComments;
From your schema comments is not an array. you are trying to spread an object into an array. const updatedComments = [...this.comments]; also push works on array.
try to modify your schema definitions by declaring the commentSchema outside the bugSchema.
const commentSchema = new Schema({
user:{
type: String,
required: true
},
content: {
type: String,
required: true
}
})
const bugSchema = new Schema({
comments: {
type: [commentSchema]
}
})
Bug.findByIdAndUpdate(bugId, {$push: {comments: newComment}})
Don't use findByIdAndUpdate Mongoose method, you better use save
it is written here https://mongoosejs.com/docs/tutorials/findoneandupdate.html
The findOneAndUpdate() function in Mongoose has a wide variety of use cases. You should use save() to update documents where possible, but there are some cases where you need to use findOneAndUpdate(). In this tutorial, you'll see how to use findOneAndUpdate(), and learn when you need to use it.
Below a router example
router.put('/items', (req, res) => {
if (!req.body._id || !req.body.title) {
return res.status(501).send({ message: 'Missing parameters, or incorrect parameters' });
}
return itemModel.findOne({ _id: req.body._id }, (err, item) => {
if (err) {
return res.status(500).send({
message: err
});
}
item.title = req.body.title; // <------------- You rewrite what was before stored on title attribute
return item.save((err, item) => { // <------------- You save it, this is not gonna create a new one, except if it doesn't exist already
if (err) {
return res.status(400).send({
message: 'Failed to update item'
});
} else {
return res.status(200).send({
message: 'Item update succesfully',
data: item
});
}
});
});
});
I'm trying to learn Meteor through a video tutorial to finish the code did not get the same result. Here is the code:
Meteor.startup(function(){
if(Meteor.users.find().count() < 1){
var users= [
{
name: "Superuser",
email: "admin#example.com",
roles: ['admin']
}
];
_.each(users, function(user){
var id;
id = Accounts.createUser({
email: user.email,
password: "password",
profile:{
name: user.name
}
});
if(user.roles.length > 0){
Roles.addUsersToRoles(id, user.roles);
}
});
}
});
It is assumed that Meteor.roles.find.().fetch () console should appear: Object name: 'admin' _id. 'whatever'; but my pops me empty [ ].
I'm using alanning: roles from atmospherejs
Thanks in advance.
Have you installed the accounts-ui and accounts-passwords packages? It might be related to that. I suggest you to install the meteortoys:allthings to check what is wrong with your DB.
Meteor.startup(function() {
if (Meteor.users.find().count() < 1) {
var users = {
name: "Superuser",
email: "admin#example.com",
roles: ['admin']
};
var id;
id = Accounts.createUser({
email: user.email,
password: "password",
profile: {
name: user.name
}
});
if (user.roles.length > 0) {
Roles.addUsersToRoles(id, user.roles, 'defaultgroup');
}
});
}