Using Ember Data to load data async from node sever - node.js

My Model :
App.Contacts = DS.Model.extend({
name : DS.attr('string'),
number : DS.attr('number')
});
This is how i save a record :
App.AddController = Ember.Controller.extend({
actions : {
addContact : function(){
var post = this.store.createRecord('Contacts',{
name : this.get('name') ,
number : this.get('number')
});
post.save();
}
}
});
Acc to Ember's offical guide, this would send a POST request to /Contacts , so to handle it, i used this in nodejs/expressjs
app.post('/contacts',function(req,res){
posts.push( req.body);
console.log(posts);
res.send({status: 'OK'});
});
Now i wish to retrieve it, into another template called all so i used :
App.AllRoute = Ember.Route.extend({
model : function(){
return this.store.find('Contacts');
},
setupController : function(controller,model){
controller.set('contactList',model);
}
});
Acc to Emberjs guides, model hook supports promises out-of-the-box . so i assumed this should work.
My template :
<script type="text/x-handlebars" id="all" >
Hello
<table>
{{#each contact in contactList}}
<tr>
<td>{{contact.name}} </td>
<td>{{contact.number}} </td>
</tr>
{{else}}
<tr><td>No contacts yet </td> </tr>
{{/each}}
</table>
</script>
Question
But the model returns nothing, i understand that this.store.find('Contacts') doesn't return a javascript array, but essentially and object , implimenting Ember.Enumerable
But on the server side, the posts is an javascript array, therefore there might be an type mismatch between then. how to resolve this?
EDIT:
To avoid any confusions in client side Ember code , This works properly, so there is some problem with the round trip to server.
App.AllRoute = Ember.Route.extend({
model : function(){
return this.store.all('Contacts');
},
setupController : function(controller,model){
controller.set('contactList',model);
}
});

If you could provide a jsfiddle, it be nice. I'm not sure whether contactList is defined or not and whether the alias for that controller is actually defined. So based on what I see, I think the problem is you're iterating over a controller that does not have the model properly defined.
I'd suggest trying to do:
{{#each}}
<tr>
<td>{{contact.name}} </td>
<td>{{contact.number}} </td>
</tr>
{{else}}
<tr><td>No contacts yet </td> </tr>
{{/each}}
If you really want to use the contactList controller, then you need to make sure that the App.AllController "needs" the contactListController.
App.ContactListController = Ember.ArrayController.extend({}) // needs to be an array controller
App.AddController = Ember.ArrayController.extend({
needs: ["contactList"], // controller's used within this controller
contactList: Ember.computed.alias("controllers.contactList"), // needed to iterate over the model how you're doing it.
Both of these solutions should work assuming your data is actually loaded in Ember Data. You might want to check the "data" tab on the ember-data console. If you don't have that browser extension installed, do it. It's incredibly useful.
If all else fails, try logging to verify expected values using {{log contactList}}
Good luck

Related

Not being able to delete an item from to-do list using Item.removeOne( ) or Item.findByIdAndRemove( ) methods of mongoose in NodeJS

I am making a to-do list using mongodb,node.js,express and EJS. The part where I am stuck is I am not being able to delete and item from the list and the database. The idea is that on clicking a checkbox, the item beside will be deleted. Here is a layout for the same,
[https://i.stack.imgur.com/83gMW.png][1]
I made the necessary changes in my EJS file to create a "/delete" route as given below :
<%for(var i=0;i<taskslist.length;i++){%>
<form action="/delete" method="POST">
<div class="item">
<input type="checkbox" name="checkitem" value="<%= taskslist[i]._id %> " onChange="this.form.submit()">
<p><%= taskslist[i].activity %> </p>
</div>
</form>
<%}%>
In my app.js folder, I also made the necessary changes by using findByIdAndRemove( ) method for mongoose :
app.post("/delete", function (req, res) {
const delitem = req.body.checkitem;
Item.findByIdAndRemove(delitem, function (err) {
if (err) {
console.log("Error");
} else {
console.log("Succesfully deleted" + delitem);
res.redirect("/");
}
});
console.log(delitem);
});
However, the item is not getting deleted from the database and an error is showing in terminal, even though the console.log(delitem) is working and returning the id of the item whose checkbox is selected.
I am also giving a screenshot of the output I am getting at the terminal:
[https://i.stack.imgur.com/hGEkn.png][1]
All the methods related to adding items and creating database are working. I don't understand where the error is. Please help me out with this.

How to send an object to .marko template and render its properties dynamically, in a table

Im doing some homework here. Build a server that handles a requisition to list all registers from a database, dynamically. Im using node js and the modules: express, marko and sqlite3. The db is set and has some registers for testing; (id, name, desc, price). The route '/planos' is set to return a promise, its .then function sends a .marko file, as first parameter, and an object, that is the result from a DAO to list all my stuff from the database, as second parameter. The DAO is working and the object with all the db registers is returning, but i cant get marko to print it in my html...
Im trying to get it right, but i dont know how to refer to the data in the object i passed to the template. A lot of "cant read 'property' of undefined" in the process...
//The route.
app.get('/planos', function(req, resp){
planoDao = new PlanoDAO(db)
planoDao.listagem().then(function(resultado){
console.log(resultado)
resp.marko(require('../views/plano/plano2.marko'), {
planos: resultado
})
})
})
//The .marko file
<table >
<tr>
<th>ID</th>
<th>Nomes</th>
<th>Descrição</th>
<th>Preços</th>
</tr>
<${out.global.planos? planos-tr : 'tr' }>
<td>${input.planos.id}</td>
<td>${out.global.nome}</td>
<td>${out.global.desc}</td>
<td>${out.global.price}</td>
</>
<if(data.planos)>
<for |{planos}| in=data.planos>
<tr>
<td>ID: ${data.id}</td>
<td>${data.planos.nome}</td>
<td>${data.planos.desc}</td>
<td>${data.planos.price}</td>
</tr>
</for>
</if>
</table>
<if(data.planos)>
<for(plano in data.planos)>
<tr>
<td>${plano.id}</td>
<td>${plano.name}</td>
<td>${plano.desc}</td>
<td>${plano.price}</td>
</tr>
</for>
</if>

accessing template params ejs express

I'm creating fleet management application, I've set up for vehicles' makes and models and I've established one-to-many relationship in my database model.
I'm trying to present the vehicle make along with its models, however, it doesn't seem to work, below is the code from my routes file:
router.get("/new",function(req,res){
var selectedMake;
Make.find({},function(err,result){
if(err){
console.log("an error occured while fetching the data");
}else{
if(req.query.id){
Make.findById(req.query.id,function(err,foundMake){
console.log("found the query string");
selectedMake = foundMake;
console.log(selectedMake);
})
}
res.render("vehicles/newvehiclemake",{makes:result,selected: selectedMake});
}
})
});
and here is the code where i'm trying to access variable "selected" in my .ejs file
<div class="row">
<div class="col-md-9 col-md-offset-3">
<table class="table table-striped">
<tr>
<th>Available Models</th>
</tr>
<% if(selected) { %>
<% selected.models.forEach(function(model){ %>
<tr><td><%= model.name %></td></tr>
<% }) %>
<% }else { %>
<tr><td>No Models available for the selected Make</td></tr>
<% } %>
</table>
</div>
</div>
the branch where selected should be executed is never reached and always i get No Models available for the selected Make
any clues?
I think that is because your Make.findById method is a asynchronous call. So your callback function(err,foundMake) is called after the res.render
Move your render call into the callback function, then it should work.
if(req.query.id){
Make.findById(req.query.id,function(err,foundMake){
console.log("found the query string");
selectedMake = foundMake;
// after the findById call finished, now it has value.
console.log(selectedMake);
// res.render should be called at this moment.
res.render("vehicles/newvehiclemake",{makes:result,selected: selectedMake});
})
// you would see this line is called before the data is ready.
console.log(selectedMake);
}

Conditionally render depending on presence of a faces message

I have a special row in my table for errors:
<tr>
<td colspan="2"><p:message for="questionId" id="msgQuestion" /></td>
</tr>
How can I set this so the row is only displayed when there is an error?
In first place i will recommend not to use table to display layout elements
after that the ellement will apear even if the message is not present, if you are obliged to use it you can use som think like this in JS:
<script type="text/javascript">
window.onload = function() {
hideTdMessage();
};
hideTdMessage(){
var message = document.getElementById(msgQuestion);
if(message){
//the msg is present
}else{
//the msg is not present
}}
</script>
Or You can use your MBean to change the CSS class it's better than using JS.
But i will say that the best solution is not tu use the tabel.
Hope it helped
Use a JSF component and the property rendered
rendered="#{not empty facesContext.messageList}"

React.js key generation

I've a problem with the Reconciliation algorithm using a set of key (without duplicates). The snippet of code is similar to the examples:
`
var ResourceTable = React.createClass({
getInitialState: function() {
return {data: [{"rid": "Ciao ", "id": 10}, {"rid": "Mondo!", "id": 2}]};
},
componentDidMount: function() {
self = this;
self.setState({data: [{"rid":"first", "id": 3},{"rid":"second", "id": 1},{"rid":"third", "id": 2}]});
},
render: function() {
var commentNodes = this.state.data.map(function (resource, index) {
return (
<Resource key={resource.id} rid={resource.rid}/>
);
});
return(
<table>
{commentNodes}
</table>
);
}
});
`
The first time that the object is rendered everything works fine (for every value of the resource.id). The second time I've an unattended behavior: sometimes every element is correctly rendered and sometimes not, I made a lot of attempts, but I cannot find an explanation.
The case that cause the error is:
First rendering keys: [10,2]
Second rendering keys: [3,1,2]
The result is that only two element are rendered during the second rendering.
React is very sensitive if you are rendering HTML which is mutating in browser. This is the case with <table>, which can be created like this:
<table>
<tr><td>Cell</td></tr>
</table>
But in fact browsers are changing it to:
<table>
<tbody>
<tr><td>Cell</td></tr>
</tbody>
</table>
After this operation DOM and React Virtual DOM differs and triggers errors like yours. To fix it just change:
return (
<table>
{commentNodes}
</table>
);
into:
return (
<table>
<tbody>{commentNodes}</tbody>
</table>
);

Resources