Nodejs verify array strings - node.js

I have array of strings and I need to validate if incoming text id is included any of string in my array or not, how can I do that in node? (in php we usually do in_array()) but in node I don't have much experience.
sample code
var text = msg;
var myArray = [
"123",
"456"
];
if(text.id == myArray) {
// true
} else {
// false
}
PS: I am aware that if(text.id == myArray) is wrong, I just wrote that so you can get the idea of what I'm looking for.
Update
My current code
var myArray = [
"182700619",
"1566587158"
];
if (myArray.includes(msg.forward_from.id)) {
console.log("msg2:", true);
} else {
console.log("msg2:", false);
}
my incoming message structure
msg = {
message_id: 221,
from: {
id: 1566587158,
is_bot: false,
first_name: 'Test User',
username: 'testuser',
language_code: 'en'
},
chat: {
id: 1566587158,
first_name: 'Test User',
username: 'testuser',
type: 'private'
},
date: 1619746446,
forward_from: {
id: 182700619,
is_bot: false,
first_name: 'John',
last_name: 'Doe',
username: 'johndoe'
},
forward_date: 1619694506,
text: 'tesing 01!'
}

You can do it with below code, by using toString() method to convert the int to strings and then compare it.
msg = {
message_id: 221,
from: {
id: 1566587158,
is_bot: false,
first_name: 'Test User',
username: 'testuser',
language_code: 'en'
},
chat: {
id: 1566587158,
first_name: 'Test User',
username: 'testuser',
type: 'private'
},
date: 1619746446,
forward_from: {
id: 182700619,
is_bot: false,
first_name: 'John',
last_name: 'Doe',
username: 'johndoe'
},
forward_date: 1619694506,
text: 'tesing 01!'
}
var myArray = [
"182700619",
"1566587158"
];
console.log(typeof msg.forward_from.id);
if (myArray.includes(msg.forward_from.id.toString())) {
console.log("msg2:", true);
} else {
console.log("msg2:", false);
}
Output of the above code is below
$node main.js
number
msg2: true

Related

Why does the child's resolve function not contain the result of the parent's resolve function?

I've tried to isolate this example and I hope it's ok. I know, this isn't great code, but I hope you get the drift.
For the time being the resolvers return a static result object.
Here's my problem:
The result of the company resolve function should be passed on the user's resolve function. But that ain't happenin' and I wonder what I am missing.
const GraphQL = require('graphql');
const UserType = new GraphQL.GraphQLObjectType({
name: 'User',
fields: {
givenName: { type: GraphQL.GraphQLString },
familyName: { type: GraphQL.GraphQLString },
city: { type: GraphQL.GraphQLString },
},
});
const CompanyType = new GraphQL.GraphQLObjectType({
name: 'Company',
fields: {
legalName: { type: GraphQL.GraphQLString },
city: { type: GraphQL.GraphQLString },
employees: { type: new GraphQL.GraphQLList(UserType) },
},
});
const queryDef = new GraphQL.GraphQLObjectType({
name: 'Query',
fields: {
user: {
type: UserType,
args: {
id: { type: GraphQL.GraphQLID },
givenName: { type: GraphQL.GraphQLString },
familyName: { type: GraphQL.GraphQLString },
city: { type: GraphQL.GraphQLString },
},
resolve: (parent, args, context, info) => {
console.log('parent should provide company object', parent);
// currentyl parent is undefined
return {
id: 10,
givenName: 'test',
};
},
},
company: {
type: CompanyType,
args: {
id: { type: GraphQL.GraphQLID },
},
resolve: (parent, args, context, info) => {
return {
id: 3,
legalName: 'legal test name',
city: 'company location',
};
},
},
},
});
const schema = new GraphQL.GraphQLSchema({ query: queryDef });
const companyQuery = `
{
company(id: 1) {
city
employees {
familyName
}
}
}`;
GraphQL.graphql(schema, companyQuery).then( (companyResult) => {
console.log(companyResult);
} ).catch( (err) => {
console.error(err);
});

Need to push data in nested subdocument array

I need to push data in nested subdocument array(replyComment):
This is an example of a document from my database:
{
comments: [
{
replyComment: [],
_id: 601a673735644c83e0aa1be3,
username: 'xyz123#gmail.com',
email: 'xyz213#gmail.com',
comment: 'test123'
},
{
replyComment: [],
_id: 601a6c94d1653c618c75ceae,
username: 'xyz123#gmail.com',
email: 'xyz123#gmail.com',
comment: 'reply test'
}
],
_id: 601a3b8038b13e70405cf9ea,
title: 'latest test',
snippet: 'latest test snippet',
body: 'latest test body',
createdAt: 2021-02-03T05:58:24.123Z,
updatedAt: 2021-02-03T12:28:33.237Z,
__v: 7
}
I am also mentioning my code snippet:
app.post('/:id/replyComment',(req,res) => {
const replyComm = new Comment(req.body);
Topic.findById(req.params.id)
.then((result) => {
topic = result,
console.log(topic);
topic.update({_id:req.params.id, "comments._id": req.body.comment_id},
{ $push: {"comments.$.replyComment": {replyComment: replyComm}}}
)
topic.save()
.then((result) => {
// console.log(result);
res.send({
text: "Replied",
})
})
.catch((err) => {
console.log(err);
});
})
});
By running the request I am not getting any error but still the same documented is getting printed on my terminal and there is no change in "replyComment" subarray.
Pls suggest how to make this work or any alternate method.
I prefer to use objects instead of arrays by converting objects to the array Object.keys(data.comments)
{
comments:
{
'601a673735644c83e0aa1be3':{
username: 'samyakjain971#gmail.com',
email: 'samyakjain971#gmail.com',
comment: 'test123'
}
},
{
'601a6c94d1653c618c75ceae':{
username: 'samyakjain971#gmail.com',
email: 'samyakjain971#gmail.com',
comment: 'reply test'
}
},
_id: 601a3b8038b13e70405cf9ea,
title: 'latest test',
snippet: 'latest test snippet',
body: 'latest test body',
createdAt: 2021-02-03T05:58:24.123Z,
updatedAt: 2021-02-03T12:28:33.237Z,
__v: 7
}
define topic variable like this :
let topic = result;
console.log(topic);
topic.update({_id:req.params.id, "comments._id": req.body.comment_id},
{ $push: {"comments.$.replyComment": {replyComment: replyComm}}}
)

is there a way to find and return a property if it has a specific value?

What I want is that in users query it returns the email data whenever private is false.
this is my scheme
const userSchema = new Schema({
email: {
private: {
type: Boolean,
default: false,
},
data: {
type: String,
unique: true,
required: true,
},
},
password: {
type: String,
required: true,
}
})
I tried to do it this way, but it doesn't work because it is not dynamic.
const user = await User.find({}, '-email.data')
the result I am looking for is this
[
{ _id: 0, email: { private: true } },
{ _id: 1, email: { private: false, data: 'email#email.com' } }
]
Try $cond operator, check if email.private is true then return only private property otherwise full email object
const user = await User.find({},
{
email: {
$cond: [
{ $eq: ["$email.private", true] },
{ private: true },
"$email"
]
}
})
Playground

mongoose schema create empty array by default?

Im new to mongoose and mongoDB, by a tutorial, I have a user schema looks like this:
var userSchema = mongoose.Schema({
local: {
email: {
type: String,
index: {
unique: true,
dropDups: true
}
},
password: String,
displayName: String,
avatar: {
type: String,
default: "./img/user.png"
},
role: {
type: String,
default: "student"
},
ask_history: [
{
question_id: {
type: mongoose.Schema.Types.ObjectId,
ref: 'questionAnswer'
},
favorite: Boolean,
ask_time: Date
}
],
interest: [String]
},
facebook: {
id: String,
token: String,
email: String,
displayName: String,
avatar: String,
familyName: String,
givenName: String,
gender: String,
ageMin: Number,
role: {
type: String,
default: "student"
},
ask_history: [
{
question_id: {
type: mongoose.Schema.Types.ObjectId,
ref: 'questionAnswer'
},
favorite: Boolean,
ask_time: Date
}
],
interest: [String]
},
twitter: {
id: String,
token: String,
email: String,
name: String,
avatar: String,
role: {
type: String,
default: "student"
},
ask_history: [
{
question_id: {
type: mongoose.Schema.Types.ObjectId,
ref: 'questionAnswer'
},
favorite: Boolean,
ask_time: Date
}
],
interest: [String]
}
}, {strict: true});
It creates user record by the way user is sign up for, either give local email or using oauth register by 3rd party.
Schema above will generate a document looks like this if I create a local user:
{
"_id": {
"$oid": "58792ee6e8a08204a0d68f7a"
},
"twitter": { ////////////////////////////////////////
"interest": [], //
"ask_history": [], //
"role": "student" //
}, // <-- nothing should created for a local user
"facebook": { //
"interest": [], //
"ask_history": [], //
"role": "student" //
}, ////////////////////////////////////////
"local": {
"password": "$2a$10$OtdbF7t52TyNAuwZXFT0u.Q/A.E5TeV4T.shHCxSSxDll2nX4bCbW",
"displayName": "aaa",
"email": "aaa#gmail.com",
"interest": [],
"ask_history": [],
"role": "admin",
"avatar": "./img/user.png"
},
"__v": 0
}
The problem I'm having is at
ask_history: [
{
question_id: {
type: mongoose.Schema.Types.ObjectId,
ref: 'questionAnswer'
},
favorite: Boolean,
ask_time: Date
}
],
interest: [String]
With out those array declaration in the schema the document looks just fine for any type of the user, for example, a local user, document would looks like this (no facebook or twitter field):
var userSchema = mongoose.Schema({
local: {
email: {
type: String,
index: {
unique: true,
dropDups: true
}
},
password: String,
displayName: String,
avatar: {
type: String,
default: "./img/user.png"
},
role: {
type: String,
default: "student"
}
},
facebook: {
id: String,
token: String,
email: String,
displayName: String,
avatar: String,
familyName: String,
givenName: String,
gender: String,
ageMin: Number,
role: {
type: String,
default: "student"
}
},
twitter: {
id: String,
token: String,
email: String,
name: String,
avatar: String,
role: {
type: String,
default: "student"
}
}
}, {strict: true});
{
"_id": {
"$oid": "5874d1d0cd045371b4e96eca"
},
"local": {
"password": "$2a$10$KpnIE2Uc2tX.YfcQCGm6EeDMexFFZXbKJVcQvxltBxrTkxb8E7mH.",
"displayName": "aaa",
"avatar": "./img/user.png",
"email": "aaa#gmail.com",
"role": "admin"
},
"__v": 0
}
And this is my function for creating a local user:
passport.use('local-signup', new LocalStrategy({
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true
}, function(req, email, password, done) {
if (!req.body.name || req.body.name.length == 0) {
return done(null, false, req.flash('signupMessage', 'Name can\'t be empty'));
}
User.findOne({
'local.email': email
}, function(err, user) {
if (err) {
return done(null, false, req.flash('signupMessage', 'Error: ' + err));
} else {
if (validator.validate(email)) {
if (user) {
return done(null, false, req.flash('signupMessage', 'Email already registered.'));
} else {
var newUser = new User();
newUser.local.email = email;
newUser.hashPassword(password);
newUser.local.displayName = req.body.name;
newUser.save(function(err) {
if (err) {
throw err;
}
return done(null, newUser);
});
}
} else {
return done(null, false, req.flash('signupMessage', 'Email not vaild'));
}
}
});
}));
My question is how can I set the schema to when the document is created, the array will not be created.
I think for your exact question the answer would be:
Arrays are special because they implicitly have a default value of [] (empty array).
const ToyBox = mongoose.model('ToyBox', ToyBoxSchema);
console.log((new ToyBox()).toys); // []
To overwrite this default, you need to set the default value to undefined
const ToyBoxSchema = new Schema({
toys: {
type: [ToySchema],
default: undefined
}
});
This is from the mongoose v6.4.4 docs but as I checked the
But on the other hand maybe you should create a schema for your subdocuments and set the default value for them to undefined. That would also do the trick and would be more exact definition.
app: {
type: AppDataSchema, // AppDataSchema is a schema defined elsewhere
default: undefined,
},
To create an empty array, you need to use default: null.
If you use undefined instead, the schema will not create the array at all because undefined is not a value but null is.
Try this:
const ToyBoxSchema = new Schema({
toys: {
type: [ToySchema],
default: null
}
});

mongoose js populate embedded objects in array

I am trying to display a list of subject names associated with a training event, however the object id is the only property that is populated after the query has executed. I have tried the solution in this QUESTION which seems to be similar to what I am trying to achieve, but it is not working.
My load method is at the very bottom of this code snippet.
Any help is appreciated, thanks.
var UserSchema = new Schema({
firstName: {
type: String,
trim: true,
default: '',
validate: [validateLocalStrategyProperty, 'Please fill in your first name']
},
lastName: {
type: String,
trim: true,
default: '',
validate: [validateLocalStrategyProperty, 'Please fill in your last name']
},
displayName: {
type: String,
trim: true
}
});
var SubjectSchema = new Schema({
name: {
type: String,
default: '',
required: 'Please fill subject name',
trim: true
},
description: {
type: String,
default: '',
required: 'Please fill subject description',
trim: true
}
});
var TrainingSubjectSchema = new Schema({
subject: {
type: Schema.ObjectId,
ref: 'Subject'
},
attendanceRate:[{
type: Number
}]
});
var TrainingEventSchema = new Schema({
name: {
type: String,
default: '',
required: 'Please fill training event name',
trim: true
},
created: {
type: Date,
default: Date.now
},
user: {
type: Schema.ObjectId,
ref: 'User'
},
attendees:[{
type: Schema.ObjectId,
ref: 'User'
}],
subjects:[TrainingSubjectSchema]
});
// retrieve method
Training.findById(id).populate('user', 'displayName').populate('subjects.subject','name').exec(function(err, trainingevent)
Not sure why it is not working in your side but I have tried
in my code and it is working as expected.
Here it is how I am creating the Schemas:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
mongoose.connect('mongodb://localhost:27017/mongoose_benn');
var UserSchema = new Schema({
firstName: {type: String, trim: true, default: ''},
lastName: {type: String, trim: true, default: ''},
displayName: {type: String, trim: true}
});
var SubjectSchema = new Schema({
name: {
type: String,
default: '',
required: 'Please fill the subject name.',
trim: true
},
description: {
type: String,
default: '',
required: 'Please fill subject description',
trim: true
}
});
var TrainingSubjectSchema = new Schema({
subject: {type: Schema.ObjectId, ref: 'Subject'},
attendanceRate: [{type: Number}]
});
var TrainingEventSchema = new Schema({
name: {
type: String,
default: '',
required: 'Please fill the training event name.',
trim: true
},
created: {type: Date, default: Date.now},
user: {type: Schema.ObjectId, ref: 'User'},
attendes: [{
type: Schema.ObjectId,
ref: 'User'
}],
subjects: [TrainingSubjectSchema]
});
module.exports = {
User: mongoose.model('User', UserSchema),
Subject: mongoose.model('Subject', SubjectSchema),
TrainingSubject: mongoose.model('TrainingSubject', TrainingSubjectSchema),
TrainingEvent: mongoose.model('TrainingEvent', TrainingEventSchema)
};
And here I am processing data with the models:
var async = require('async');
var models = require('./models.js');
var User = models.User;
var Subject = models.Subject;
var TrainingSubject = models.TrainingSubject;
var TrainingEvent = models.TrainingEvent;
async.waterfall(
[
clearDB.bind(null, {collections: [User, Subject, TrainingSubject, TrainingEvent], async: async}),
createUsers.bind(null, {User: User, async: async}),
createSubjects.bind(null, {async: async, Subject: Subject}),
createTrainingEvents.bind(null, {async: async, TrainingEvent: TrainingEvent}),
showTrainingEvents.bind(null, {TrainingEvent: TrainingEvent})
]
);
function createTrainingEvents(data, db, next) {
var firstSubject = db.subjects[0];
var secondSubject = db.subjects[1];
var trainingSubjects = [
{
subject: firstSubject._id,
attendanceRate: [5, 5]
},
{
subject: secondSubject._id,
attendanceRate: [4, 4, 5]
}
];
var trainingEvents = [
{
name: 'October Fest',
user: db.users[0]._id,
subjects: [trainingSubjects[0]],
attendes: [db.users[0]._id, db.users[1]._id]
},
{
name: 'August Fest',
user: db.users[1]._id,
subjects: [trainingSubjects[1]],
attendes: [db.users[0]._id, db.users[1]._id]
}
];
data.async.map(
trainingEvents,
function(trainingEvent, done) {
data.TrainingEvent.create(trainingEvent, done);
},
function(err, result) {
next(err);
}
);
}
function clearDB(data, next) {
async.map(
data.collections,
function(collection, done) {
collection.remove({}, done);
},
function(err) {
next(err);
}
);
}
function createUsers(data, next) {
var users = [
{firstName: 'Wilson', lastName: 'Balderrama', displayName: 'Wily'},
{firstName: 'Santiago', lastName: 'Balderrama', displayName: 'Santi'},
{firstName: 'Keila', lastName: 'Balderrama', displayName: 'Kei'}
];
data.async.map(
users,
function(user, done) {
data.User.create(user, done);
},
function(err, results) {
next(err, {users: results});
}
);
}
function showUsers(data, next) {
data.User.find({}, function(err, users) {
next();
});
}
function createSubjects(data, db, next) {
var subjects = [
{
name: 'JavaScript for Beginners',
description: 'JS fundamentals'
},
{
name: 'Node.JS for Beginners',
description: 'Node.JS streams'
}
];
data.async.map(
subjects,
function(subject, done) {
data.Subject.create(subject, done);
},
function(err, result) {
db.subjects = result;
next(err, db);
}
);
}
function createTrainingSubjects(data, db, next) {
var firstSubject = db.subjects[0];
var secondSubject = db.subjects[1];
var trainingSubjects = [
{
subject: firstSubject._id,
attendanceRate: [5, 5]
},
{
subject: secondSubject._id,
attendanceRate: [4, 4, 5]
}
];
data.async.map(
trainingSubjects,
function(trainingSubject, done) {
data.TrainingSubject.create(trainingSubject, done);
},
function(err, result) {
db.trainingSubjects = result;
next(err, db);
}
);
}
function showTrainingSubjects(data, next) {
data.TrainingSubject
.find({})
.populate('subject')
.exec(function(err, data) {
next();
});
}
function showSubjects(data, next) {
data.Subject.find({}, function(err, data) {
next();
});
}
function showTrainingEvents(data, next) {
data.TrainingEvent
.find({name: 'August Fest'})
.populate('user', 'displayName')
.populate('subjects.subject', 'name')
.exec(function(err, data) {
console.log(JSON.stringify(data));
next();
});
}
And the output is;
[
{
"_id":"55981d58cfd48c905c3a5fde",
"user":{
"_id":"55981d58cfd48c905c3a5fd8",
"displayName":"Santi"
},
"__v":0,
"subjects":[
{
"subject":{
"_id":"55981d58cfd48c905c3a5fdb",
"name":"Node.JS for Beginners"
},
"_id":"55981d58cfd48c905c3a5fdf",
"attendanceRate":[
4,
4,
5
]
}
],
"attendes":[
"55981d58cfd48c905c3a5fd7",
"55981d58cfd48c905c3a5fd8"
],
"created":"2015-0704T17:52:24.181Z",
"name":"August Fest"
}
]

Resources