how do i store ng-repeat array form data in meanjs? - javascript

I am using MEANJS from meanjs.org.
trying to store ng-repeat array data for deal which has dealtype and dealprice as array under it, but unable to do so.
i have setup addFields for the ng-repeat input tag in the create form, but it does not store the data. here is my code.
food.server.model.js
var FoodSchema = new Schema({
created: {
type: Date,
default: Date.now
},
name: {
type: String,
default: '',
required: 'Please fill Food name',
trim: true
},
deal: [{
dealtype: {
type: String,
default: '',
trim: true
},
dealprice: {
type: String,
default: '',
trim: true
}
}],
user: {
type: Schema.ObjectId,
ref: 'User'
}
});
foods.client.controller.js
// initial array setup
var deal = [ { dealtype: '',dealprice: '' }, {dealtype: '',dealprice: '' } ];
$scope.food = {};
$scope.food.deal = deal;
$scope.addItem = function() {
$scope.food.deal.push({
dealtype: '',
dealprice: ''
});
};
// Create new Food
$scope.create = function (isValid) {
$scope.error = null;
if (!isValid) {
$scope.$broadcast('show-errors-check-validity', 'foodForm');
return false;
}
// Create new Food object
var food = new Foods({
name: this.name,
deal:[{
dealtype: this.dealtype,
dealprice: this.dealprice,
}],
});
// Redirect after save
food.$save(function (response) {
$location.path('foods/' + response._id);
// Clear form fields
$scope.name = '';
$scope.dealtype = '';
$scope.dealprice = '';
}, function (errorResponse) {
$scope.error = errorResponse.data.message;
});
};
create-food.client.view.html
<form name="foodForm" class="form-horizontal" ng-submit="create(foodForm.$valid)" novalidate>
<fieldset>
<div class="col-md-12">
<md-input-container flex="">
<label >Food Name</label>
<input type="text" data-ng-model="name" id="name" required>
</md-input-container>
</div>
<div ng-repeat="de in food.deal">
<div class="col-md-6">
<md-input-container class="">
<label class="" for="dealtype">Dealtype</label>
<input type="text" data-ng-model="de.dealtype" id="dealtype" >
</md-input-container>
</div>
<div class="col-md-6">
<md-input-container class="">
<label class="" for="dealprice">Dealprice</label>
<input type="text" data-ng-model="de.dealprice" id="dealprice" >
</md-input-container>
</div>
</div>
<a href ng:click="addItem()" class="btn btn-small">add item</a>
<button class="md-primary md-raised width-100 md-whiteframe-5dp" type="submit">Create Food</button>
<div ng-show="error" class="text-danger">
<strong ng-bind="error"></strong>
</div>
</fieldset>
</form>

Try to set your schema up without the embedded array and send without deal. If that works you may need to set up your schema with a subdocument.
If you are wanting to set your deal property up as a Subdocument you would need to follow this. You would define a schema for deal separately. Something like this:
var dealSchema = new Schema({ {
dealtype: {
type: String,
default: '',
trim: true
},
dealprice: {
type: String,
default: '',
trim: true
}
} });
var FoodSchema = new Schema({
...,
deal: [dealSchema]
})

Related

Loop Through all users to send email Node JS

I tried finding the answer but couldn't. I'm new to Node Js and have a user schema that includes users emails. I want to have a form that has 'subject' and 'message' fields, and a submit button which would then send the contents of the form in an email. I'm currently using Mailgun, and a standard email looks like this:
var data = {
to: user.email,
from: '"Lighthouse Studios" <noreply#reception.lighthousespace.co.uk>',
subject: 'Your password has been changed',
text: 'Hello,\n\n' +
'This is a confirmation that the password for your account ' + user.email + ' has just been changed.\n'
};
mailgun.messages().send(data, function (error, body) {
console.log(body);
});
And my user schema looks like:
var UserSchema = new mongoose.Schema({
username: {type: String, unique: true, required: true},
name: {type: String, required: true},
email: {type: String, unique: true, required: true},
password: String,
studio: {type: String, required: true},
resetPasswordToken: String,
resetPasswordExpires: Date,
comments: [
{
quantity: String,
received: { type: Date, default: Date.now },
collected: { type: String, default: "At Reception" }
}
],
isAdmin: {type: Boolean, default: false}
});
Here's the form code:
<form action="/" method="POST">
<div class="form-group">
<input class="form-control" type="text" name="subject" placeholder="Subject">
</div>
<div class="form-group">
<textarea class="form-control" rows="5" id="comment" name="message" placeholder="Message"></textarea>
</div>
<div class="form-group">
<input class="btn btn-lg btn-primary btn-block" type="submit" value="Send">
</div>
</form>
So to summarise, I want to use the form to send all users an email when the button 'submit' is clicked. Thanks for your time reading this.
UserModel.find({})
.select('email')
.lean()
.exec((err,users)=>{
if(users){
let userEmails = "";
let recp = users.reduce((a,u)=>{ a[u.email]={}; a[u.email].email = u.email; userEmails+=u.email; return a; },{})
let data = {
to: userEmails,
from: '"Lighthouse Studios" <noreply#reception.lighthousespace.co.uk>',
subject: 'Your password has been changed',
text: 'Hello,\n\n' +'This is a confirmation that the password for your account ' + %recipient.email% + ' has just been changed.\n',
'recipient-variables': JSON.stringify(recp)
};
mailgun.messages().send(data, function (error, body) {
console.log(body);
});
}
})
Hope this one will work

Creating new array with variables coming back as undefined

I am creating a blog web application. I currently have the blogSchema set up as
var BlogSchema = new mongoose.Schema({
title: String,
image: String,
body: String,
created:
{type: Date, default: Date.now},
author: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
username: String
},
comments: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Comment"
}
]
});
module.exports = mongoose.model("Blog", BlogSchema);
I have a post form of the following
<div class="ui main text container segment">
<div class="ui huge header">New Blog</div>
<form class="ui form" action="/blogs" method="POST">
<div class="field">
<label>Title</label>
<input type="text" name="blog[title]" placeholder="title">
</div>
<div class="field">
<label>Image</label>
<input type="text" name="blog[image]" placeholder="image">
</div>
<div class="field">
<label>Blog Content</label>
<textarea name="blog[body]"></textarea>
</div>
<input class="ui violet big basic button" type="submit">
</form>
</div>
On my blog routes page I have my create route as
router.post("/blogs", function(req, res){
// create blog
//req.body.blog.body = req.sanitize(req.body.blog.body);
var title = req.body.title;
var image = req.body.image;
var desc = req.body.body;
var author= {
id: req.user._id,
username: req.user.username
}
var newBlogpost = {title: title, image: image, body: desc, author: author}
Blog.create(newBlogpost, function(err, newBlog){
if(err){
res.render("blogs/new");
} else {
//then, redirect to the index
console.log(newBlogpost)
res.redirect("/blogs");
}
});
});
However when I sign in on the web application and complete the form and view my commmand line for the return of console.log(newBlogpost) after I submit, I get:
{ title: undefined,
image: undefined,
body: undefined,
author: { id: 5a0cbcc3d6c7070a7bb6c45e, username: 'cat' }
I am not sure why the new variable array I am creating has these three variable as undefinded and would appreciate help.

The correct way to display cards in lists, as in Trello

I'm trying to create project like Trello. I do not know how to do it properly.
I created function init in AngularJS Controller where i put http requests:
$scope.loadLists();
$scope.loadsCards();
Scripts:
$scope.loadLists = function () {
return ApiService.staff.list()
.then(function (resp) {
for (var i = 0; i < resp.length; i++) {
$scope.lists[i] = resp[i];
}
})
}
$scope.loadsCards = function () {
return ApiService.staff.cards()
.then(function (resp) {
for (var i = 0; i < resp.length; i++) {
$scope.cards = resp;
}
console.log($scope.cards)
})
}
I'm downloading tasks to $scope.cards
In console.log() we can see:
Array [ Object, Object, Object, Object, Object, Object, Object, Object ]
where the object consists of
var CardSchema = new Schema({
name: { type: String, maxlength: 20, required: true },
list: { type: Schema.Types.ObjectId, ref: 'List' },
updated: { type: Date, default: Date.now },
created: { type: Date, default: Date.now },
active: Boolean
});
And now I do not know what to do so that the cards are displayed only those in the given column that are assigned to the list. I mean : task.list == list._id
for the moment I did it
<div ng-repeat="list in lists track by $index">
<div style="float: left; margin-left: 5px;">
<div id="tasks">
<h3>{{list.name}}</h3>{{$index}}
<ul>
<li ng-repeat="task in cards">
<div ng-hide="task.list == list._id">
{{task.name}}
</div>
<i ng-click="removeTask(task)" class="fa fa-trash-o"></i></li>
</ul>
<form ng-submit="addTask(list._id, $index, newTask)">
<input type="text" ng-model="newTask" placeholder="add a new task" required />
</form>
</div>
</div>
</div>
But it does not work and so it probably can not be if I want to still create a database for the card field
Position (Later to enable drag & dropping)
Can anyone tell me how to properly display cards in lists?
EDIT;;;
thank you very much for the help.
Can you explain more to me because I still have a problem with the cards
I did directiv in angularJS:
App.directive('myList', function() {
return {
restrict: 'E',
replace: true,
template: '<div style="float: left; margin-left: 5px;"><div id="tasks">{{list.name}}<br>{{card.name}}</div></div>'
};
});
App.directive('myCard', function() {
return {
restrict: 'E',
replace: true,
template: '<div style="float: left; margin-left: 5px;"><div id="tasks">{{card.name}}</div></div>'
};
});
and in index.ejs
<my-list ng-repeat="list in lists" list-data="list"></my-list>
<my-card ng-repeat="card in listData.cards" card-data="card"></my-card>
I also did AJAX inquiry after all cards :
https://gist.github.com/anonymous/ed17c3fd675ea4361cb8fbd78e94cb37
name: its name card
list: its _id list
In $scope.cards I stores AJAX inquiry after all cards,
Its my card model
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var CardSchema = new Schema({
name: { type: String, maxlength: 20, required: true },
// description: { type: String, maxlength: 300 },
list: { type: Schema.Types.ObjectId, ref: 'List' },
updated: { type: Date, default: Date.now },
created: { type: Date, default: Date.now },
active: Boolean
});
module.exports = mongoose.model('Card', CardSchema);
And I have no idea how this loop looks, would you help me somehow?
It's not that easy to solve with two ng-repeat's. You may want to create your list and card directives because eventually they will be complex views:
<my-list ng-repeat="list in lists" list-data="list"></my-list>
And in my-list directive, you can create a loop to to render cards:
<my-card ng-repeat="card in listData.cards" card-data="card"></my-card>

ERROR SyntaxError: Unexpected token < in JSON at position 0

ERROR:
core.es5.js?0445:1084 ERROR SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>
SITUATION:
What I am trying to achieve is to pre-select the choice the user already made previously and prevent him from voting twice.
CODE:
component.html
<article class="panel panel-default">
<div class="panel-body">
{{ poll.title }}
<br>
<br>
<form #form="ngForm">
<fieldset [disabled]="alreadyVotedFor(-1)">
{{ poll.counter1 }} votes <input type="radio" id="{{ poll.choice1 }}" name="my_radio" value="{{ poll.choice1 }}" (click)="onChoice1(form)" [checked]="alreadyVotedFor(1)"> {{ poll.choice1 }}
<br>
{{ poll.counter2 }} votes <input type="radio" id="{{ poll.choice2 }}" name="my_radio" value="{{ poll.choice2 }}" (click)="onChoice2(form)" [checked]="alreadyVotedFor(2)"> {{ poll.choice2 }}
</fieldset>
</form>
</div>
<footer class="panel-footer">
<div class="author">
{{ poll.username }}
</div>
<div class="config" *ngIf="belongsToUser()">
<a (click)="onEdit()">Edit</a>
<a (click)="onDelete()">Delete</a>
</div>
</footer>
</article>
component.ts
votes: any;
ngOnInit() {
this.pollService.voted(this.poll, localStorage.getItem('userId')).subscribe(
data => {
this.votes = data.votes;
console.log("NGONINIT this.votes: "+ this.votes);
},
err => { console.log("NGONINIT ERROR: "+ err) },
() => { console.log("SUBSCRIBE COMPLETE this.votes: "+ this.votes); }
);
}
alreadyVotedFor(choice: number) {
let result = "";
if (this.votes) {
console.log("THIS.VOTES: "+this.votes);
for (var i = 0; i < this.votes.length; i ++) {
if (this.votes[i].poll == this.poll.pollId) {
result = "disabled";
if (this.votes[i].choice == choice) {
result = "selected";
}
}
}
}
return result;
}
service
voted(poll: Poll, userID: string) {
return this.http.get('http://localhost:3000/'+userID)
.map(response => response.json());
}
routes/user.js
router.get('/:userid', function (req, res, next) {
var userId = req.params.userid;
User.findById(userID, function (err, user) {
console.log("USER JSON? :"+user.json());
return res.send(user.json());
});
});
models/user
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var mongooseUniqueValidator = require('mongoose-unique-validator');
var schema = new Schema({
firstName: {type: String, required: true},
lastName: {type: String, required: true},
password: {type: String, required: true},
email: {type: String, required: true, unique: true},
polls: [{type: Schema.Types.ObjectId, ref: 'Poll'}],
votes: [{
poll: {type: Schema.Types.ObjectId, ref: 'Poll'},
choice: {type: Number},
}],
});
schema.plugin(mongooseUniqueValidator);
module.exports = mongoose.model('User', schema);
This error happens when server responds with HTML instead of JSON, particularly when a route is not found and the response is 404 page.
It's unlikely that API has the only route which is mounted at root and available as http://localhost:3000/'+userID, just because it's not possible for the server to do anything else in this case.
If the route is mounted to some path, like
app.use('/user', userRoutes);
then the requests should be performed to this path as well
return this.http.get('http://localhost:3000/user/'+userID)

How to add an array to a javascript server side model in MEAN.JS

I am using MEAN.JS and I have created a module for projects. I would like to add tasks to these projects and I would like to do it with a multi-dimensional array. I would like the array to include a task.description and a task.status which would both be strings. I think I understand the client-side part of my project and I know there are still other files. However, I believe this will make the question as simple as possible, as I am struggling to get my profile developed on this site. I will however include controller.js, so I can get this working and hopefully give credit for a correct answer.
project.server.model.js
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
/**
* Project Schema
*/
var ProjectSchema = new Schema({
created: {
type: Date,
default: Date.now
},
title: {
type: String,
default: '',
trim: true,
required: 'Title cannot be blank'
},
description: {
type: String,
default: '',
trim: true
},
/* MODEL for TASK ARRAY*/
task: {
},
user: {
type: Schema.ObjectId,
ref: 'User'
}
});
mongoose.model('Project', ProjectSchema);
projects.server.controller.js
'use strict';
/**
* Module dependencies.
*/
var path = require('path'),
mongoose = require('mongoose'),
Project = mongoose.model('Project'),
errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller'));
/**
* Create a project
*/
exports.create = function (req, res) {
var project = new Project(req.body);
project.user = req.user;
project.save(function (err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.json(project);
}
});
};
/**
* Show the current project
*/
exports.read = function (req, res) {
res.json(req.project);
};
/**
* Update a project
*/
exports.update = function (req, res) {
var project = req.project;
project.title = req.body.title;
project.description = req.body.description;
project.save(function (err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.json(project);
}
});
};
edit-project.client.view.html
<section ng-controller="ProjectsController" ng-init="findOne()">
<div class="page-header">
<h1>Edit Project</h1>
</div>
<div class="col-md-12">
<form name="projectForm" class="form-horizontal" ng-submit="update(projectForm.$valid)" novalidate>
<fieldset>
<div class="form-group" show-errors>
<label for="title">Title</label>
<input name="title" type="text" ng-model="project.title" id="title" class="form-control" placeholder="Title" required>
<div ng-messages="projectForm.title.$error" role="alert">
<p class="help-block error-text" ng-message="required">Project title is required.</p>
</div>
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea name="description" ng-model="project.description" id="description" class="form-control" cols="30" rows="4" placeholder="Description"></textarea>
</div>
<div class="form-group">
Task Description
<textarea name="description" ng.model="project.task.description" class="form-control" cols="30" rows="3" placeholder="Description"></textarea>
<div>
Task Status
<input name="status" ng.model="project.task.status" class="form-control" placeholder="Status">
</div>
</div>
<div class="form-group">
<input type="submit" value="Update" class="btn btn-default">
</div>
<div ng-show="error" class="text-danger">
<strong ng-bind="error"></strong>
</div>
</fieldset>
</form>
</div>
</section>
First, create a model for tasks (task.server.model.js), which references a Project
var TaskSchema = new mongoose.Schema({
description: String,
status: String,
// referencing Project model
project: { type: mongoose.Schema.Types.ObjectId, ref: 'Project' }
});
And then in Project model reference Task
// Add this to Project Schema definition
tasks: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Task' }]
It's should
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
/**
* Task Schema
*/
var TaskSchema = new Schema({
description: String,
status: String,
project: {
type: Schema.ObjectId,
ref: 'Project'
}
});
Hope it's help you!

Categories

Resources