I am trying to post data from front-end to RESTful. I'm a backbone beginner, so my problems are probably easy to solve. But have struggled with this all day - so now I'm asking for guidance.
I have a button that use to add data to REST. So in my view I use object.save(); to save an object to model.
Here is my model:
define(["underscore" , "backbone"],function(_ , Backbone){
var Test = Backbone.Model.extend({
url:'http://mysite.com/Test/Test.svc/AddTest',
idAttribute: 'ID'
});
return Test;
});
View :
define(["jquery" ,
"underscore" ,
"backbone" ,
'models/Test',
'views/Test',
],function($ , _ , Backbone , Test, TestView){
var HomeView = Backbone.View.extend({
initialize: function() {
//....
},
events : {
"click #byn" : function(){
//....
},
'click #test' : 'addTest'
},
addTest : function(){
var object = new Test();
object.set({
"ID" : 0,
"Name" : "",
"CustomerID" : 106,
"Type" : 0,
"LastUpdated" : "\/Date(1383152400000+0700)\/",
"Detail" : [
{
"ID" : 0,
"TID" : 0,
"ItemID" : 22776,
"Quantity" : 2,
"LastUpdated" : "\/Date(1383152400000+0700)\/"
}
]
});
object.save();
var _wlView = new TestView({model:object});
},
render : function(){
//....
}
});
return HomeView;
});
To be truth, I really don't know how could I post the object that I have saved in my view object.save(); to the restful throw the rest url like http://mysite.com/Test/Test.svc/AddTest.
Url of model should be declared as urlRoot value and it is better to have it relative (e.g. "/AddTest").
Then the backend route for save action will be "actual url" + "urlRoot".
Related
I have a nested array in MongoDB database that I wish to display on the frontend using Jade and Express.
I am having some trouble displaying them:
This is the nested items I wish to display:
MongoDB:
{
"_id" : ObjectId("5c3343913d1e1323111fce6f"),
"title" : "Projecten",
"__v" : 0,
"sub_items" : [
{
"title" : "item1"
},
{
"title" : "item2"
}
]
}
Mongoose Model:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var menuItems = new mongoose.Schema({
sub_items : {
title: String
}
}, {collection: 'menu_items'});
module.exports = mongoose.model("menu_items", menuItems);
I post the nested items with Express like this:
postController.updateSubItems = function(req,res,item) {
var id = req.body.id;
var saveData = {
title: req.body.sub_item
};
item.update({_id: id}, {$addToSet:{sub_items: saveData}}, (err, result) => {
});
};
Display in jade like this:
each item in data
p #{item.sub_items}
Eventually it comes out like this:
item1,item2
Like a string, though I want to display them like single items
Try below code, as per your sub_items object
each item in [{sub_items:'sub_item_1'}]
p=item.sub_items
Paste above code into this editor
Not sure if there's a more elegant way to do this in Jade, but I just used the editor suggested by #iamwebkalakaar, tested the following snippet and it appears to print correctly:
each item in [{"sub_items" : [{"title" : "item1"}, {"title" : "item2"}]}]
each subitem in item.sub_items
p=subitem.title
New snippet
- var data = { "title" : "Projecten", "__v" : 0, "sub_items" : [ { "title" : "item1" }, { "title" : "item2" } ] };
each subitem in data.sub_items
p=subitem.title
Im having trouble that my userid ( aka _id created by mongodb) wont let me search .
here is my user
db.users.find({})
{ "_id" : ObjectId("5912073cd87a401dd196a820"), "password" : "$2a$10$Sj/bxhSzeL8xzZYn8Vl71OjrG9Ayly9ueDi2O1iDwi7N4vYyZGWKi", "username" : "malin", "inFamily" : false, "bank" : 500, "defence" : 1, "attack" : 1, "cash" : -494055600, "xp" : 0, "rank" : 1, "bullets" : 0, "location" : 1, "permission" : 0, "health" : 0, "__v" : 0 }
as seen here its one with id 5912073cd87a401dd196a820 .
Here is the function im always calling.
function userDetails(userid) {
return new Promise(function(resolve, reject) {
console.log("search: " + userid);
// Users.findById(userid, function (result) {
Users.findOne({_id: userid},function(result) {
console.log("search done");
console.log(result);
return resolve(result);
});
});
}
I use the function all over my site, on some things its works, others it wont.
For example. when component 1 calls it it works, when component 2 tries, it fails.
None of the findByid or findOne works when its failing.
Here is the query my site ran on one of my components that is failing:
search: 5912073cd87a401dd196a820
Mongoose: users.findOne({ _id: ObjectId("5912073cd87a401dd196a820") }, { fields: {} })
logging /api/gameapi?action=getcrimemembers
navigate: false
search done
null
But every results is null/ false, how come?
Use this i'ts must work good. Mongoose function already returned promise so you don't need wrap it in function:
Users.findOne({_id: userid}).then(result=>{...}).catch(err=>{...})
Hi I have a combo box which have a store that is based on rest call and populate data from data base, its working fine but i need a value 'All' with all the values coming from data base so how can i do this please suggest
var wardName = Ext.create('Ext.data.Store', {
id : 'visittype',
fields : [
{
name : 'id',
type : 'integer',
},
{
name : 'wardName',
}
],
remoteGroup : true,
remoteSort : true,
proxy : {
type : 'rest',
url : 'pmsRest/wards',
reader : {
root : "wardMaster",
idProperty : 'id'
}
},
autoLoad : true,
});
{
xtype : 'combo',
name : 'wardName',
labelStyle : 'color:black;font-weight:bold;width:250px;padding:10;',
labelSeparator : "",
id : 'wardName',
width:'33%',
fieldLabel : 'Ward',
triggerAction : 'all',
store : wardName,
displayField : 'wardName',
valueField : 'id',
multiSelect : false,
typeAhead : true,
//disabled: true,
listeners : {
change : function(combo) {
Ext.getCmp('bedName').bindStore(loadBedName());
}
},
allowBlank : false,
//enableKeyEvents : true,
},
Once the data from the proxy is loaded successfully you can use the insert method of store to add the static data in store.
insert method inserts Model instances into the Store at the given index.
The syntax is store.insert( index, records ) where index is the position at which you want to insert the instance, in this case it would be 0.
hope it helps you. :-)
Add a listener to the store and a load event. In that event you can add a new item to the store when the store is loaded.
listeners: {
load: function(){
this.add({
id: 0,
name: 'All'
});
}
}
I'm trying to read firebase data and then print the data to the console, but nothing makes it to the console.
function readData(){
var listRef = new Firebase('https://----.firebaseIO.com/');
listRef.on('child_added', function(snapshot) {
var msgData = snapshot.val();
console.log("Snapshot : " + msgData.message);
});//end snapshot
}//end readData
my firebase data looks like. This is right under the root.
{
"-J75NmiNt3blUhVDCWbc" : {
"from" : "Blah",
"message" : "Blah"
},
"-J75N2bNbDZpshEBG1yS" : {
"from" : "Jackson",
"message" : "BLAH BlaH"
},
"-J75PCsjFlbDQ3g9vKyb" : {
"from" : "fff",
"message" : "fff"
},
"-J75MvQQpRBB6s-l3KrQ" : {
"from" : "",
"message" : ""
},
"-J75OHX7rdE1K8wpvZOt" : {
"from" : "fff",
"message" : "ff"
}
} //end
EDIT: My original answer was completely missing question, rewritten for further smiting
Are you sure that you are getting the data within your Event? It would gracefully fail. Step through the debugger and make sure you are getting your actual object passed correctly. From their example on the chat tool They are binding to an event that pushes to the listRef object like this:
$('#messageInput').keypress(function (e) {
if (e.keyCode == 13) {
var name = $('#nameInput').val();
var text = $('#messageInput').val();
messagesRef.push({name:name, text:text});
$('#messageInput').val('');
}
});
My guess is that your snapshot variable is not accessible/null.
I've run into some strange differences between the mongodb running on MongoHQ and the version running on my own development machine. Specifically, when calling .toString() on an object id inside a MapReduce map function, the results vary:
On my own machine:
ObjectId('foo').toString() // => 'foo'
On MongoHQ:
ObjectId('foo').toString() // => 'ObjectId(\'foo\')'
Note: The id's I use are actual mongodb id's - not just 'foo' etc. as in these examples
I would expect .toString() to behave like on my own machine - not how it's behaving on MongoHQ. How come it's not?
My local OSX version of MongoDB is installed using Homebrew and is version 2.0.1-x86_64
To show what's actually going on, I've build a little test case. Let's assume that we have a users collection with a friends attribute, being an array of user ids:
> db.users.find()
{ _id: ObjectId('a'), friends: [ObjectId('b'), ObjectId('c')] },
{ _id: ObjectId('b'), friends: [] },
{ _id: ObjectId('c'), friends: [] }
As you can see a is friends with b and c where as b and c isn't friends with anybody.
Now let's look at a working test-algorithm:
var map = function() {
this.friends.forEach(function(f) {
emit(f, { friends: 1, user: user, friend: f.toString() });
});
};
var reduce = function(k, vals) {
var result = { friends: 0, user: [], friend: [] };
vals.forEach(function(val) {
result.friends += val.friends;
result.user.push(val.user);
result.friend.push(val.friend);
});
return result;
};
var id = ObjectId('50237c6d5849260996000002');
var query = {
query : { friends: id },
out : { inline: 1 },
scope : { user: id.toString() },
jsMode : true,
verbose : true
};
db.users.mapReduce(map, reduce, query);
Assuming id is set to an id of a user who is a friend of someone in the users collection, then the output returned by the mapReduce method on MongoHQ will look like this:
{
"results" : [
{
"_id" : ObjectId("50237c555849260996000001"),
"value" : {
"friends" : 1,
"user" : "50237c6d5849260996000002",
"friend" : "ObjectId(\"50237c555849260996000001\")"
}
},
{
"_id" : ObjectId("50237c74c271be07f6000002"),
"value" : {
"friends" : 1,
"user" : "50237c6d5849260996000002",
"friend" : "ObjectId(\"50237c74c271be07f6000002\")"
}
}
],
"timeMillis" : 0,
"timing" : {
"mapTime" : 0,
"emitLoop" : 0,
"reduceTime" : 0,
"mode" : "mixed",
"total" : 0
},
"counts" : {
"input" : 1,
"emit" : 2,
"reduce" : 0,
"output" : 2
},
"ok" : 1,
}
As you can see, the friend attribute in each result is not just a string containing the id, but a string containing the actual method call.
Did I run this on my own machine, the results array would have been:
{
"_id" : ObjectId("50237c555849260996000001"),
"value" : {
"friends" : 1,
"user" : "50237c6d5849260996000002",
"friend" : "50237c555849260996000001"
}
},
{
"_id" : ObjectId("50237c74c271be07f6000002"),
"value" : {
"friends" : 1,
"user" : "50237c6d5849260996000002",
"friend" : "50237c74c271be07f6000002"
}
}
MongoHQ is running a different version of MongoDB than you are.
To get the behavior of your homebrew version, try changing your map function:
var map = function() {
this.friends.forEach(function(f) {
emit(f, { friends: 1, user: user.str, friend: f.str });
});
};