So I have a problem with my var array to add a new chapter, how would I go about this would I have to do this:
array.push({
chapter: [
{
id: 2,
title: 'adsf',
content: '',
authorNotes: 'asdf'
}
]
});
RiTest.ts
import * as mongoose from 'mongoose';
const Scheme = mongoose.Schema;
export const RiTestScheme = new Scheme({
novelName: String,
novelAuthor: String,
novelCoverArt: String,
novelTags: Array,
chapters: [
{
id: Number,
title: String,
content: String,
authorNotes: String
}
]
});
export class RiTestController {
public addChapter(callback: (data) => void) {
var chapterInfoModel = mongoose.model('ChaptersTest', RiTestScheme);
var array = [
{
chapter: [
{
id: 0,
title: 'prolog',
content: 'conetntt is empty',
authorNotes: 'nothing is said by author'
},
{
id: 1,
title: 'making a sword',
content: 'mine craft end chapter',
authorNotes: 'nothing'
}
]
}
];
let newChapterInfo = new chapterInfoModel(array);
newChapterInfo.save((err, book) => {
if (err) {
return callback(err);
} else if (!err) {
return callback(book);
}
});
}
}
This doesn't work, var array doesn't get saved into let newChapterInfo = new chapterInfoModel(array); what I am trying to do add another chapter to array.chapter but the array doesn't get recognized in the chapterInfoModel() how would I fix this array and add an item to the array to create a new entry into this existing collection
thank for taking your time to answer my question.
You are trying to insert array of document to your collections, That the reason its not inserting into your collection.
Document.prototype.save() will insert only one document to your collection depends on your definition. So to insert chapter here is the code below,
//array as Object
var array = {
chapter: [
{
id: 0,
title: 'prolog',
content: 'conetntt is empty',
authorNotes: 'nothing is said by author'
},
{
id: 1,
title: 'making a sword',
content: 'mine craft end chapter',
authorNotes: 'nothing'
}
]
};
//Push to your chapter array
array.chapter.push({
id: 2,
title: 'adsf',
content: '',
authorNotes: 'asdf'
});
let newChapterInfo = new chapterInfoModel(array);
Related
Here I am trying to modify my data over the iteration and send some result to API call.
The API Call receives a request with a structured data format which is
{ list: [{ id: "1", name: "Hello" }, ... ] }
Somehow I managed to call the API with single data ( const params in my current code, it only accepts single data).
But now it has to be done with multiple data something like this:
{ list: [{ id: "1", name: "Hello" }, { id: "22", name: "Ed" }, { id: "36", name: "Jason" } ... ] }
Here is my current code
const [table, setTalbe] = useState(..); // assume, we have some table data here
const processNow = () => {
let id = 0;
let name = '';
// if table length is greater than 1, we go for the loop.
if (table.length >= 1) {
table.map(data => {
id = data.userId;
name = data.userName;
});
//insert table data to params, here I want to add whole table data into "list"
//the final result of this list should be something like this
//ex ) list: [{ id: '123', name: 'Josh' }, { id: '125', name: 'Sue' }, { id: '2222', name: 'Paker' } ...],
// but how??
const params: any = {
list: [
{
id: id,
name: name
},
],
};
//send PUT reqeust with params
axios
.put(
'/api/v1/tosent',
params,
)
.then(res => {
console.log('The response', res);
})
.catch(err => {
console.log('The error: ', err);
});
}
};
but I'm stuck with it, please help me to finish this code to work properly.
need your kind advice.
Array.prototype.map returns a new array with the function you pass applied to every element. You should study the MDN documentation on map to understand its use.
Your current code does nothing with the map return value:
table.map(data => {
id = data.userId;
name = data.userName;
});
You probably assumed .map would mutate the data, as in change it in place. Instead, the whole operation returns a new array.
It looks like you want to do:
const list = table.map(data => {
return {
id: data.userId,
name: data.userName
}
});
This is applying a function to every element in the array that will map each element to a new object, matching your question, with an id and name key. Then it looks like you want to pass the returned value of map (which we named list above) to your call:
const params: any = {
list: list
};
I am trying to create a nested JSON object using NodeJS. I am getting data from the JIRA software server and trying to map to my application's schema. Below is my application's schema.
schema:
Product:
_id: ObjectId
categories: [Category]
backlog: [Section]
Category:
_id: ObjectId
name: String
color: String
Section:
_id: ObjectId
title: String
backlogItems: [BacklogItem]
BacklogItem:
_id: ObjectId
productId: ObjectId
title: String
description: String
category: Category
acceptanceCriteria: [AcceptanceCriterion]
tasks: [Task]
notes: [Note]
I want to create one category for tasks. For example, if there are two or more issues from JIRA of type "Epic", I want to create only one category and then I want to create an array of BacklogItems but it is giving me below error:
categories: [Category], Category is not defined
Below is what I am trying to do:
function parseResponse(body) {
var data = JSON.parse(body);
result.product = {
id: ObjectID(),
categories: [Category],
backlog: [Section]
};
for (var i = 0; i < data.issues.length; i++) {
var color;
var categoryName;
switch (data.issues[i].fields.issuetype.name) {
case "Story":
color = "green";
break;
case "Epic":
color = "purple";
break;
case "Task":
color = "blue";
break;
case "Bug":
color = "red";
break;
}
var uniqeCategory = [
...new Set(data.issues.map(x => x.fields.issuetype.name))
];
if (uniqeCategory[i] !== data.issues[i].fields.issuetype.name) {
categoryName = uniqeCategory[i];
} else {
categoryName = data.issues[i].fields.issuetype.name;
}
console.log(uniqeCategory);
result.product.backlog.push({
id: ObjectID(),
title: "importer",
backlogItem: []
});
result.product.backlog.backlogItem.push({
id: data.total,
productId: result.product.id,
title: data.issues[i].fields.summary,
description: data.issues[i].fields.description,
category: data.issues[i].fields.issuetype.name,
acceptanceCriteria: [],
tasks: [],
notes: []
});
Can somebody try to tell me what I am doing wrong and How can I create such an object?
PS: I just started working with NodeJS and trying to learn it by doing it.
After some efforts, I tried to create an object. Below is my code.
for (var j = 0; j < issue.fields.attachment.length; j++) {
var note = {
_id: ObjectID(),
createdAt: issue.fields.attachment[j].created,
content: issue.fields.attachment[j].filename,
attachmentUrl: issue.fields.attachment[j].content,
attachmentPreviewUrl: issue.fields.attachment[j].thumbnail
};
notesArray.push(note);
}
/* Creating seaparate notes by taking comments from each JIRA issue and put it in form of note */
for (var k = 0; k < issue.fields.comment.comments.length; k++) {
var note = {
_id: ObjectID(),
createdAt: issue.fields.comment.comments[k].created,
content: issue.fields.comment.comments[k].body,
attachmentUrl: "",
attachmentPreviewUrl: ""
};
notesArray.push(note);
}
/* Creating backlog items */
result.product.backlog.push({
_id: ObjectID(),
productId: result.product._id,
title: issue.fields.summary,
description: issue.fields.description,
category: issue.fields.issuetype.name,
acceptanceCriteria: [],
tasks: [],
notes: notesArray
});
console.log("final", result.product);
});
How do I insert into the database the array structure of objects as a string?
$scope.lists = [
{
label: "Parcerias Principais",
allowedTypes: ['p1'],
class: "b1",
people: []
},
{
label: "Atividades Principais",
allowedTypes: ['p2'],
class: "b2",
people: []
}
];
$scope.salvar = function(){
$http.post('link', {
aluno: 1,
tarefa: $scope.lists,
data: new Date(),
dataultima: new Date(),
curso: 82}).then(function(resultado){
$ret = resultado.data;
console.log($ret);
});
}
expected outcome:
enter image description here
I want to insert my direct array into the SQLSERVER database in this way.
Try JSON.stringify as used below :
$scope.salvar = function(){
$http.post('link', {
aluno: 1,
tarefa: JSON.stringify($scope.lists),
data: new Date(),
dataultima: new Date(),
curso: 82}).then(function(resultado){
$ret = resultado.data;
console.log($ret);
});
}
heres my output Image html How can I delete Object in array and push when adding some Data
angular.module('myApp.Tree_Service', [])
.factory('TreeService', function() {
var svc = {};
var treeDirectories = [
{
name: 'Project1',
id: "1",
type: 'folder',
collapse: true,
children: [
{
name: 'CSS',
id: "1-1",
type: 'folder',
collapse: false,
children: [
{
name: 'style1.css',
id: "1-1-1",
type: 'file'
},
{
name: 'style2.css',
id: "1-1-2",
type: 'file'
}
]
}
]
}
];
svc.add = function () {}
svc.delete = function (item, index) { }
svc.getItem = function () { return treeDirectories; }
return svc;
});
})();
I'm Newbee in Angularjs and I don't know how much to play it.
Hopefully someone can help me. Im Stucked.
Well you can delete any object by just usingdelete Objname.property
So for example you want to delete Children in treeDirectories first index object you can use delete treeDirectories[0].children if you want to delete children inside children then delete treeDirectories[0].children[0].children
if you want to remove an index from an array in lowest level children then
treeDirectories[0].children[0].children.splice(index,1)
for pushing data is for object you can directly assign value to the property you want
treeDirectories[0].children[0].newproperty = "check"
And for array you can
treeDirectories[0].children[0].children.push(object)
I've an array that contains assignments of employees on tasks, it looks like something like this:
$scope.assignments = [
{
employee: {
id:"1", firstname:"John", lastname:"Rambo"
},
task: {
name:"Kill everyone", project:"Destruction"
},
date: {
day:"01/01", year:"1985"
}
},
{
employee: {
id:"2", firstname:"Luke", lastname:"Skywalker"
},
task: {
name:"Find daddy", project:"Star Wars"
},
date: {
day:"65/45", year:"1000000"
}
},
{
employee: {
id:"1", firstname:"John", lastname:"Rambo"
},
task: {
name:"Save the world", project:"Destruction"
},
date: {
day:"02/01", year:"1985"
}
}
];
I would like to group by employee, for having something like this:
$scope.assignmentsByEmployee = [
{ //First item
id:"1",
firstname:"John",
lastname:"Rambo",
missions: [
{
name:"Kill everyone",
date:"01/01",
year:"1985"
},
{
name:"Save the world",
date:"02/01",
year:"1985"
}
]
},
{ //Second item
id="2",
firstname:"Luke",
lastname:"Skywalker",
missions: [
name:"Find daddy",
date:"65/45",
year:"1000000"
]
}
];
Is their a simple way to do this ? I tried something with a double forEach, but it leads me nowhere.
Hope I'm understandable :)
Thanks !
You should just be able to loop through the assignments array and create a 'keyed array' (which just means using an object in JavaScript) on employee ID. Then you just fill up the missions array as required.
Something like
// initialise a holding object
var assignmentsByEmployee = {};
// loop through all assignemnts
for(var i = 0; i < $scope.assignments.length; i++) {
// grab current assignment
var currentAssignment = $scope.assignments[i];
// grab current id
var currentId = currentAssignment.employee.id;
// check if we have seen this employee before
if(assignmentsByEmployee[currentId] === undefined) {
// we haven't, so add a new object to the array
assignmentsByEmployee[currentId] = {
id: currentId,
firstname: currentAssignment.employee.firstname,
lastname: currentAssignment.employee.lastname,
missions: []
};
}
// we know the employee exists at this point, so simply add the mission details
assignmentsByEmployee[currentId].missions.push({
name: currentAssignment.task.name,
date: currentAssignment.date.day,
year: currentAssignment.date.year
});
}
These leaves assignmentsByEmployee as an object, but you can simply foreach through it and convert it back to an array if required. E.g:
$scope.assignmentsByEmployee = [];
for(var employeeId in assignmentsByEmployee) {
$scope.assignmentsByEmployee.push(assignmentsByEmployee[employeeId]);
}