angularjs formly basic form not working - angular-formly

I'm new in angularjs-formly and this is my first try and I could not get my form working , please just be patient with me this is my first question and may be other questions will come after this one.
Here is my code :
my plunker :https://plnkr.co/edit/sxr64SXYZQ8yjtnOU3a2?p=preview
Please tell me what's wrong with this piece of code ?
Thank you.
/koul

I fixed your plunker:
https://plnkr.co/edit/T0AAG5mY80hDNzVLKoKp?p=preview
(function() {
// Code goes here
angular
.module('plunker', ['formly', 'formlyBootstrap'])
.controller('mainCtrl', function($scope) {
console.log('mainCtrl is Loaded');
var vm = this;
vm.fields = [{
key: 'id',
type: 'input',
templateOptions: {
type: 'number',
label: 'Id',
placeholder: 'Enter Id',
required: true
}
}, {
key: 'name',
type: 'input',
templateOptions: {
type: 'text',
label: 'Name',
placeholder: 'Enter ur Name',
required: true
}
}];
});
})();
You were missing the extra "}" after the templateOptions on the first one, and there were a few other things I did. I usually wrap any js files in a closure, and its not good practice to use var with angular, you just type angular then .module or .controller. If you are just learning angular, you should ditch the controllers and learn components, as that is the proper way now.
Also, the references to the libraries were not correct...some of those links don't work anymore. A quick look at the debugger, via F12 would have shown those as being problematic.

Related

Sequelize magic method not found using Express and Node.JS

I'm coding an application using Sequelize, Express and Node.JS; after set a OneToMany relationship between User and Product, just like this:
app.js:
Product.belongsTo(User, { constraints: true, onDelete: 'CASCADE' });
User.hasMany(Product);
and from a controller called admin.js I'm trying to create a new Product using a magic method:
admin.js:
exports.postAddProduct = (req, res, next) => {
const title = req.body.title;
const imageUrl = req.body.imageUrl;
const price = req.body.price;
const description = req.body.description;
req.user.createProduct({
title: title,
imageUrl: imageUrl,
price: price,
description: description
})
.then((result) => {
console.log("Record successfully created");
return res.redirect("/admin/products");
})
.catch((err) => {
console.log(err);
});
};
postAddProduct is triggered after submit a form, the error I'm getting is this:
So, my question is: based on sequelize's official documentation, after define a relationship I can use methods for create, edit o search an entity, what am I missing to get access to these methods?
thanks for your comments
even though my model is called Product, the table's name is newproducts, so, in order to solve this I made this change:
req.user.createNewproduct({
title: title,
imageUrl: imageUrl,
price: price,
description: description })
After this, problem solved
Nice to see someone else taking Max's Node.js course!
I had this same problem. For me, it stemmed from the fact that I defined how my id column works differently. Instead of this...
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true
},
...I did this...
id: {
type: Sequelize.UUID,
defaultValue: Sequelize.UUIDV4,
allowNull: false,
primaryKey: true,
},
and utilized the uuid package to make unique Product and User IDs. Because of this, I had to update how I defined my SQL relations in app.js:
Product.belongsTo(User, { constraints: true, onDelete: "CASCADE" });
User.hasMany(Product, { foreignKey: "id" });
So if you're using a custom ID generator or something, make sure to specify that you are in the options object and the function should appear!
You can read more about this in the docs: https://sequelize.org/docs/v6/core-concepts/assocs/#defining-the-sequelize-associations
Hope this helps!

Is there a way to set up mongoose to check if two values match in a single schema?

I'm new to node.js and am required to do some basic validation to check if two fields (in this case, passwords) match and if it doesn't, to display an error message. I'm not worrying about encryption at this point because it's outside of the scope as this is the last part of a uni task.
I've tried creating variables that it can pass on to another but that didn't help much.
Here's a shortened snippet of what I have.
Schema:
const customerSchema = new mongoose.Schema(
{
password:
{
type: String,
required: true,
},
rePassword:
{
type: String,
required: true,
},
Posted
app.post("/", function(req,res)
{
let newCustomer = Customer(
{
password: req.body.cPass,
rePassword: req.body.cConfPass,
Any help is appreciated :)
Solved!
Turns out I needed to do it just before I ran the function later and it looks like
if(req.body.cPass != req.body.cConfPass)
{
console.log("passwords don't match")
}
else
{
newCustomer.save();
}

Multilanguage interface and content with mongo / node

We are developing a new app which will be served online in saas model. User will get access to certain tools and some tutorials on how to use it.
My question is what will be the best approach to make both (interface and content) multilingual. To give you an example - imagine simple navigation with following links:
-section 1
|-page a
|-page b
-section 2
-section 3
|-page c
Each page includes obviously certain labels, titles, buttons etc.
I've been searching for a while and the closest answer I found was here:
Schema for a multilanguage database
however, it describes approach regarding a relational database.
After studying other questions it look like the best approach would be to store each name of section/page/label/title/button as an object with ID keep translation in a separate table including the corresponding ID of the object, language and content. Within SQL world simple join would do the work, however since we are using Mongo I guess there is the better way to do that so.
I would propose to store all translations in your mongoDb database, and then, using an Express API, perform request from the front page about the translations.
[FRONT] ----> [Send mongoDB _id(s)] ---> [EXPRESS API] ===> [MONGOOSE]
[FRONT] <---------- [Translations] <---- [EXPRESS API] <=== [MONGOOSE]
Mongoose Schema
const Content = Schema({
// Type of item you are dealing with
contentType: {
type: String,
enum: ['link', 'title', 'section', 'page'],
},
// Value of translations
translations: [{
languageName: String,
value: String,
}],
// All Contents that are inside
childs: [{
type: Schema.Types.ObjectId,
ref: 'Content',
}],
});
Example of data (MongoDB Document)
[{
_id: '00000000000000000000001',
contentType: 'section',
translations: [{
languageName: 'French',
value: 'Section Enfant',
}, {
languageName: 'English',
value: 'Child Section',
}],
dads: ['00000000000000000000002'],
}, {
_id: '00000000000000000000002',
contentType: 'page',
translations: [{
languageName: 'French',
value: 'Page Baguette',
}, {
languageName: 'English',
value: 'Tee Page',
}],
childs: [],
}]
Example of Request: Retrieve all data about one random section
Content.find({
contentType: 'section',
})
.then((ret) => {
if (!ret) return [];
// Here recursively get childs and childs and childs
// until you got everything
})
.then(() => {})
.catch(err => {});
Tools
Mongoose
----> Mongoose Queries
----> Mongoose Populate
Express
PS: Here is a github project that explains how to start a web/node project from scratch (tools to install ...etc) [Babel, Gulp, Webpack, ES6...]

Why Mongoose Populate Required?

Using mongoose populate:
http://mongoosejs.com/docs/populate.html
It seams that mongoose is forcing me to declare a ref value for populate when I first create the document but in my case i don't have the ref info yet. When I try to create a new document while providing an empty string I get to my developer field I get:
{"message":"Cast to ObjectId failed for value \"\" at path \"developer\"","name":"CastError","type":"ObjectId","value":"","path":"developer"}
Object that I'm saving through mongoose:
var Project = {
name: 'Coolproject',
status: 'pending',
developer: '',
type: 'basic',
};
Project.create(req.body, function(err, project) {
if(err) { return handleError(res, err); }
return
});
My Model:
var ProjectSchema = new Schema({
name: String,
status: {type:String, default:'pending'},
developer:{type: Schema.Types.ObjectId, ref: 'User'},
type:String
});
Basically I need to set it later, but it doesn't seam like this is possible. Currently my work around is populate it with a dummy user until later but this is less than desirable.
Thoughts?
Update
Realized that if i provide a object id like value (55132a418b3cde5546b01b37) it lets me save the document. Very odd. Guess it just figured it can find the document moves on. Wondering why this doesn't happen for a blank value.
The problem is explained in the error message. You cannot save an Empty String in the place of an ObjectId. The field is not listed as 'required', so there is no problem leaving it out and saving the document.
Code correction:
// you can save this
var Project = {
name: 'Coolproject',
status: 'pending',
type: 'basic',
};
You need to use the sparse index in model.
So, the valid model can have developer equal to nil
var ProjectSchema = new Schema({
name: String,
status: {type:String, default:'pending'},
developer:{type: Schema.Types.ObjectId, ref: 'User', sparse:true},
type:String
});
See
http://mongoosejs.com/docs/api.html#schematype_SchemaType-sparse and
http://docs.mongodb.org/manual/core/index-sparse/
for additional info

Saving a value into an array of objects in Express/Angular/Node

I'm still getting the hang of Express/Angular and how they work together to post to the server. I'm using the MEAN stack in my sample application.
The Schema for the object I'm trying to post looks like this in Express.
First define the 'Version' Schema:
var VersionSchema = new Schema({
title: {
type: String,
default: '',
trim: true
},
content: {
type: String,
default: '',
trim: true
},
submitted: {
type: Date,
default: Date.now
},
user: {
type: Schema.ObjectId,
ref: 'User'
}
});
The Version Schema is used in my Draft Schema. When a user creates a draft, it becomes a Version item in the versions array. When the draft is updated, it creates a new array item so all versions of the draft are saved.
var DraftSchema = new Schema({
versions: [VersionSchema],
});
The Draft Schema is set up as an Angular Service and injected into my controller. The service is boilerplate code for creating a $resource though so shouldn't be necessary.
I have two controllers to create the Draft object and save to Mongo: one with Angular, one with Express.
Angular controller:
$scope.create = function() {
var version = {
title: this.title,
content: this.content
};
var draft = new Drafts({
versions: [version]
});
draft.$save(function(response) {
$location.path("drafts/" + response._id);
});
};
In the angular controller I'm passing the title and contents to be saved to the Draft. As I understand it, you should not use an Angular controller to pass user information to the server. So this is handled by Express in the controller below.
Express controller:
exports.create = function(req, res) {
var draft = new Draft(req.body);
draft.versions = [req.user]; // Here is where my problem is, trying to save user
draft.save(function(err) {
if (err) {
return res.send('users/signup', {
errors: err.errors,
draft: draft
});
} else {
res.jsonp(draft);
}
});
};
You can see in my comment above where my problem is. I've looked through docs, SO questions, etc for the correct way to set my User property to the Versions array item being created here.
Note that if I move the User from the Version Schema to the Draft Schema and use:
draft.user = req.user;
To save the user then it works just fine. But I want the user to be saved into the VersionSchema.
To address Erick's comment below, this is a JSON representation of what I want my Draft model to look like. Versions is an Array because I want a new array item to be created each time the draft is updated.
[{
_id: 4h55542j232555000441,
versions: [
{
title: “A really great title”,
body: “On that day the people….”,
user: 5234523452349589hh23523,
submitted: Date
}
]
}];
draft.versions = [req.user]
Does the following: replace the versions array containing a version object with a new array containing the user object. This is not what you want.
As I see it, draft.versions has the following content:
[
{
title: '...',
content: '...'
}
]
To add a user id you need to do the following steps:
get the version object from the versions array
assign a new property to the version object and give it a value of user._id
var version = draft.versions[0]
version['user'] = req.user._id

Resources