how can i loop through an array within an object? - javascript

I want to loop through an array of objects named tier1.
what I get is this:
TypeError: Cannot read property 'length' of undefined
My code looks something like this:
module.exports.getTier1= function(curUser, callback){
for (var i = 0; i < curUser.tier1.length; i++) {
var val = curUser.tier1[i];
console.log("index: " + i + " val: " + val);
}
};
var UserSchema = mongoose.Schema({
username: {
type: String,
index:true
},
password: {
type: String
},
email: {
type: String
},
name: {
type: String
},
tier1: [Tier1]
});

Related

Converted string to json, how to get the label and data?

the value of props.record.DataUpdate.draft
{"FirstName": "This is my firstname","MiddleName": "This is my middlename","LastName": "this is my lastname"}
let newData = JSON.parse(props.record.DataUpdate.draft)
console.log(newData)
{
"FirstName": "This is my firstname",
"MiddleName": "This is my middlename",
"LastName": "this is my lastname"
}
this is my database looks like
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true,
},
tableNameToBeUpdated: {
type: Sequelize.STRING,
},
tableIdToBeUpdated: {
type: Sequelize.STRING,
},
draft: {
type: Sequelize.JSON,
},
CreatedDate: {
type: Sequelize.DATE,
},
LastUpdateDate: {
type: Sequelize.DATE,
},
status: {
type: Sequelize.STRING,
},
what I want here is to get the label (Fistname,Lastname,Middlename) with there perspective value,
note the label can be change it depends on the string that saves on draft column
how to achieve that?
Something like that:
const jsonString = {"FirstName": "This is my firstname","MiddleName": "This is my middlename","LastName": "this is my lastname"}
for (var key in jsonString) {
console.log(key + " -> " + jsonString[key]);
}
This gives me the Output:
'FirstName -> This is my firstname'
'MiddleName -> This is my middlename'
'LastName -> this is my lastname'
Edit:
Ok i took the example form your post (without the single quotes). Then just do what you posted and then use the for loop:
const jsonString = '{"FirstName": "This is my firstname","MiddleName": "This is my middlename","LastName": "this is my lastname"}'
const jsonObject = JSON.parse(jsonString)
for (var key in jsonObject) {
console.log(key + " -> " + jsonObject[key]);
}

Retrieving data from user input and save it to mongoose model

This is my model shema:
const DemoSchema = new Schema({
rowOne: {
colOne: {
one: {
name: String,
qty: Number,
},
two: {
name: String,
qty: Number,
},
three: {
name: String,
qty: Number,
},
},
},
rowTwo: {
colOne: {
one: {
name: String,
qty: Number,
},
two: {
name: String,
qty: Number,
},
three: {
name: String,
qty: Number,
},
},
},
});
When I do this it saves data to my model:
const product = await new Regal({
rowOne: { colOne: { two: { name: productName, qty: productQty } } },
});
product.save();
My question is, how can I replace rowOne, colOne and two with user input?
I tried this:
const row = req.body.rows // this must be rowOne or rowTwo
const column = req.body.column // colOne or other (colOne to colNine)
const col = req.body.col // one, two or three
const productName = req.body.name
const productQty = req.body.qty
Attempt 1:
const product = await new Regal({ `${row}`: { `${column}`: { `${col}`: { name: productName, qty: productQty }}}});
'Error --> Property Assignment expected.'
Atempt 2:
const product = await new Regal(`{${row}: { ${column}: { ${col}: { name: ${productName}, qty: ${productQty} } } } }`);
'Error --> Parameter "obj" to Document() must be an object, got {rowOne: { colOne: { one: { name: Milk, količina: 250 } } } }'
You can use variables as keys of objects using square brackets.
let user = 'username';
let newObj = { [user]:'saloni' }
this will create an object like {username:saloni}.
This way you can replace rowOne, colOne, and two with user input by storing them in a variable and then use it.

Global Count Variable not increasing

For some reason, I cannot get my global variable counter to increase, even when it increases within the function I have the count++ occurring in. My outputted results are different between the text outputted within the function and the text outside of it. Any idea what I am doing wrong here? Shouldn't the count increase on each iteration of the survey.oncomplete function results?
Survey
.StylesManager
.applyTheme("modern");
var kn2 = "LwrHXqFRN_pszCopTKHF_Q"
var kn3 = "exroCUoYl4wVzs7pKU_49w"
var count = 0
var keyname = ("kn" + count)
var mapilink = "https://images.mapillary.com/" + (keyname) + "/thumb-1024.jpg";
var json = {
pages: [
{
name: "page1",
elements: [
{
type: "image",
name: "image",
imageLink: (mapilink),
imageHeight: 580,
imageWidth: 640
},
{
type: "html",
name: (keyname),
visible: false,
html: (keyname)
},
{
type: "rating",
name: "Walkability",
title: "How walkable does this look to you"
},
{
type: "rating",
name: "Saftey",
title: "How safe does this look to you"
},
{
type: "rating",
name: "Comfortability",
title: "How comfortable does this look to you"
}
]
}
]
}
window.survey = new Survey.Model(json);
var username = document.getElementById("user").value;
survey
.onComplete
.add(function (result) {
count ++;
var PID = document.getElementById("user").value;
var results = PID + "_" + (keyname) + ":\n" + JSON.stringify(result.data, null, 3) + (count) ;
document
.querySelector('#surveyResult')
.textContent = results;
survey.clear();
survey.render();
});
$("#surveyElement").Survey({model: survey});
Got an answer from a seperate stackexchange post - basically, I needed to wrap everything in more functions.
function outputting function text rather than expected output

Mongoose: Trying to retrieve a document with (id) - getting NULL

So I am trying to retrieve a course using its id. I've tried using:
Course.findOne({ _id: __id })
Course.findById(id)
I not sure why it's not working, do I have to define _id type in the schema?
Result:
null
Here is my schema + function
const courseSchema = new mongoose.Schema({
name: { type: String, required: true, minlength: 3, max: 255 },
category: {
type: String,
required: true,
enum: ["web", "mobile", "network"]
},
tag: [String],
data: Date,
author: String,
isPublished: Boolean,
price: {
type: Number,
required: function() {
return this.isPublished;
},
min: 10,
max: 200
},
__v: Number
});
const Course = mongoose.model("Course", courseSchema);
async function updateCourse(id) {
// var __id = mongoose.Types.ObjectId(id); // tried converting string id (?)
console.log(id);
// // method 1
const course = await Course.findOne({ _id: __id });
console.log("resulting...", course);
if (!course) return;
course.isPublished = true;
course.author = "Another author";
const result = await course.save();
console.log("saved....", result);
}
updateCourse("5c726f6feb352743f8226239");
MongoDB:
You should not use __id in your Course.findOne call - use _id: _id:
Course.findOne({_id: _id});
Try to replace __id with id.
Course.findOne({_id: id});

Mongoose - How To Remove Object From Array Element [duplicate]

This question already has answers here:
Mongoose delete array element in document and save
(8 answers)
MongoDB, remove object from array
(7 answers)
Closed 5 years ago.
A user has the ability to add languages. languages are stored as an array of type teach or learn in the userschema. I can simply add a language to the languages.teach[] by using push, but how do i remove one?
language object example
let language = {
"code": FR
"level": 1
};
UserScema.js
var UserSchema = new Schema({
email: {
value: {
type: String,
lowercase: true,
//unique: true,
},
token: String,
verified: Boolean,
},
password: {
type: String,
},
phone: {
countryCode: {
type: String,
//required:true,
unique: true,
},
number: {
type: String,
required: true
},
code: String,
verified: {
type: Boolean,
default: false
},
},
jwt: String,
profile: {
username: String,
firstname: String,
lastname: String,
dob: String,
level: Number,
location: String,
image: String,
introduction: String,
},
languages: {
teach: [],
learn: [],
}
},
{
timestamps: {createdAt: 'created_at', updatedAt: 'updated_at'}
});
LanguagesController.js
destroy(req, res) {
let id = req.params.id;
let language = {
"code": req.body.code,
"level": req.body.level
};
let type = req.params.type;
User.findOne({'_id': id}, function (err, user) {
if (err) {
return res.status(404).json({
success: true,
status: 404,
data: err,
message: "User does not exist",
});
}
if (type === "teach") {
for (let i = 0; i < user.languages.teach.length; i++)
if (user.languages.teach[i].code === language.code) {
user.languages.teach[i].remove();
break;
}
}
if (type === "learn") {
//user.languages.learn.push(language);
}
console.log(user);
user.save((err, user) => {
return res.status(200).json({
success: true,
status: 201,
data: user,
message: "Successfully Deleted Language",
});
});
});
}
I tried to use .remove but im getting a user.languages.teach[i].remove is not a function.
Yes .remove is nothing on the array. You can use .filter to remove unwanted array elements.
It would be used like:
if (type === "teach") {
user.languages.teach = user.languages.teach.filter( o => o.code !== language.code)
}
This will remove all the element from the array with the condition given above.
Read more about Array.prototype.filter.
Maybe something like...
...
if (type === "teach") {
var index = user.lanauges.teach.findIndex(function(item){
return item.code === languge.code;
});
user.languages.teach.splice(index, 1);
....

Categories

Resources