I have an example setup to show my issue: http://jsfiddle.net/5xo4yzw2/1/
var root = "http://jsonplaceholder.typicode.com"
var Post = Backbone.Model.extend({
url: function(){
return this.get('url') || root + "/posts/" + this.get('id')
}
});
var Posts = Backbone.Collection.extend({
model: Post,
url: root + "/posts"
});
var posts = new Posts();
posts.fetch();
console.log("Call to collection fetch works")
var post = new Post({id: 1});
post.fetch();
console.log("Call to collection fetch works")
This example works, that is, both of the console.logs are executed without an exception being raised by .fetch(). It was my understanding, however, from both http://backbonejs.org/#Model-url and the book I am reading, that once I specify "/posts" as the collection url, the model url should be automatically resolved to [collection.url]/[id], though that is not the case. If I do not provide the url function in the model, an exception is raises upon fetching, stating the th url parameter must be provided.
Have i misunderstood something?
You haven't added your post model to your collection, in order for a model to use the collections URL it must be part of that collection.
For example
var post = new Post({id: 1});
posts.add(post);
post.fetch();
console.log("Call to collection fetch works")
Updated Fiddle
As #Artem Baranovskii pointed out, If you want to use a model outside a collection you should be using the urlRoot property. From the documentation
Specify a urlRoot if you're using a model outside of a collection, to
enable the default url function to generate URLs based on the model
id. "[urlRoot]/id" Normally, you won't need to define this. Note that
urlRoot may also be a function.
If you're using a model outside of the collection you could use urlRoot like the following:
var root = "http://jsonplaceholder.typicode.com"
var Posts = Backbone.Model.extend({
urlRoot: function () {
return this.get('url') || (root + "/posts/" + this.get('id'))
}
});
var posts = new Posts();
posts.fetch();
console.log("Call to collection fetch works")
When you execute fetch the model tries to get url by the several approaches here
Related
How can I set id of post that I'm adding? I thought that getItemNextKey() returns id that will be assigned for the post, but it's not.
AddItem(data, downloadURLs) {
data.id= this.getItemNextKey(); // Persist a document id
data.upload = downloadURLs;
// console.log('this.uploadService.downloadURLs: ' + downloadURLs);
// console.log('data.upload: ' + data.upload);
this.db.collection('items').add(data);
}
I did this and it works now.
// Add a new document with a generated id
var addDoc = this.db.collection('items').add(data).then(ref => {
var updateNested = this.db.collection('items').doc(ref.id).update({
id: ref.id
});
});
As stated in the official docs
When you use set() to create a document, you must specify an ID for
the document to create. For example:
db.collection("cities").doc("new-city-id").set(data);
If you dont want to set an ID yourself you can use add
But sometimes there isn't a meaningful ID for the document, and it's
more convenient to let Cloud Firestore auto-generate an ID for you.
You can do this by calling add():
I am using postgresql, knex, and bookshelf to make queries to update my users table. I would like to find all users who didn't sign in during a specific time and then update their numAbsences and numTardies field.
However it appears that when running a raw sql query using bookshelf.knex the result that I get for users is an array of objects rather than an array of bookshelf objects of objects because I can't save the objects directly to the database when I try to use .save(). I get the exception user.save is not a function.
Does anyone know how I can update the values in the database for the users? I've seen the update function but I need to also return the users in absentUsers so I select them currently.
// field indicates whether the student was late or absent
var absentUsers = function(field){
// returns all users who did not sign in during a specific time
if (ongoingClasses){
return bookshelf.knex('users')
.join('signed_in', 'signed_in.studentId', '=', 'users.id')
.where('signed_in.signedIn', false)
.select()
.then(function(users){
markAbsent(users, field);
return users;
});
}
}
var markAbsent = function(users, field){
users.forEach(function(user){
user[field]++;
user.save();
})
}
I've solved my problem by using another sql query in knex. It seemed there was no way to use a sql query and then use standard bookshelf knex methods since the objects returned were not bookshelf wrapper objects.
var absentUsers = function(field){
// returns all users who did not sign in during a specific time
if (ongoingClasses){
return bookshelf.knex('users')
.join('signed_in', 'signed_in.studentId', '=', 'users.id')
.where('signed_in.signedIn', false)
.select()
.then(function(users){
markAbsent(users, field);
});
}
}
var markAbsent = function(users, field){
users.forEach(function(user){
var updatedUser = {};
updatedUser[field] = user[field]+1;
bookshelf.knex('users')
.where('users.id', user.id)
.update(updatedUser).then(function(){
});
});
}
With your code bookshelf.knex('users') you leave the "Bookshelf world" and are in "raw knex world". Knex alone doesn't know about your Bookshelf wrapper objects.
You may use Bookshelf query method to get the best of both worlds.
Assuming your model class is User, your example would look approximately like
User.query(function(qb) {
qb.join('signed_in', 'signed_in.studentId', 'users.id')
.where('signed_in.signedIn', false);
})
.fetchAll()
.then(function(bookshelfUserObjects) {
/*mark absent*/
return bookshelfUserObjects.invokeThen('save'); // <1>
});
<1> invokeThen: Call model method on each instance in collection
Hi I have the next model in backboneJS:
var Type = Backbone.Model.extend({
url : "/api/SomeRoute"
});
var model = new Type({id:"MyAlias"});
model.fetch();
On the rest part In SomeRoute I have 2 actions which returns my Model. First which recieves the Id and returns the Model by Id and second without parameters which return the collection. But when I call fetch() in JS, it doesn't send the Id in the request. What I'm doing wrong?
If there is an id attribute specified in a model. Then the fetch request will be like /api/SomeROute/id
Instead of url give urlRoot. If urlRoot is specified then the models id will be appended.
var Type = Backbone.Model.extend({
urlRoot : "/api/SomeRoute"
});
Rewrite your url to next:
var type = Backbone.Model.extend({
url: function(){
return "/api/SomeRoute/" + this.get("id");
}
});
var model = new Type({id: "SomeId"});
model.fetch();
EDITED
I'm searching users in facebook using graph api in my asp.net mvc 3 application.
public void AsyncSearch(ICollection<JSonObject> result, string query, string objectType)
{
var fbClient = new FacebookClient(FacebookTokens.AccessToken);
var searchUri = string.Format("/search?q={0}&type={1}, query, objectType);
var tempResult = (JsonObject)fbClient.Get(searchUri);
var elements = (JsonArray)tempResult.Values.ToArray()[0];
elements.ForEach(element =>
{
result.Add(element);
});
var next = (JsonObject)tempResult.Values.ToList()[1];
while (next.Keys.Contains("next"))
{
tempResult = (JsonObject)fbClient.Get((string)next["next"]);
elements = (JsonArray)tempResult.Values.ToArray()[0];
elements.ForEach(element =>
{
result.Add(element);
});
next = (JsonObject)tempResult.Values.ToList()[1];
}
}
But result contains at most 600 objects(each search returns different number of objects).
I think, if i put, for example, "anna" in query parameter - result must be over 10000.
Why is that? Is there any way to retrieve all users by some keyword?
For performance concerns Facebook will paginate their results. If you look at the end of the JSON object, there should be a pageing object that has next and previous links in it. So, to get all results you will need to run multiple queries and aggregate them up on your side.
I want to retrieve the last inserted _id, using mongoose as MongoDB wrapper for node.js. I've found the following tutorial, but I can't change any node modules because the app runs on a public server:
Getting "Last Inserted ID" (hint - you have to hack Mongoose)
Any other ideas? This what I want to do:
Insert new user
Get user's _id value
Set a new session based on user's id
Redirect to /
Thanks!
I'm using mongoose version 1.2.0 and as soon as I created a new instance of a mongoose model, the _id is already set.
coffee> u = new User()
[object Object]
coffee> u._id
4dd68fc449aaedd177000001
I also verified that after I call u.save() the _id remains the same. I verified via MongoHub that this is indeed the real ID saved into MongoDB.
If you explicitly declare
_id: Schema.ObjectId
for your model, then the ObjectId will not be available after new or save.
This is probably a bug.
If you're looking to get the last inserted _id of a sub object, then create the object, and add it to the item. Here's an example in NowJS using MongoDB and Mongoose (to add some schema sugar) which then converts the result to JSON to send back to the client:
var nowRoomID = this.now.room;
var Conversation = mongoose.model('Conversation');
Conversation.findById(convID, function(error, conversation) {
var Blip = mongoose.model('Blip');
var createdBlip = new Blip();
createdBlip.author= nowUserName;
createdBlip.authorid = parsed.authorid;
createdBlip.body = revisedText;
createdBlip.created_at = new Date();
createdBlip.modified_at = new Date();
conversation.blips.push(createdBlip);
parsed._id = createdBlip._id; //NOTE: ID ACCESSED HERE
message = JSON.stringify(parsed);
conversation.save(function (err) {
if (!err) {
console.log('Success - saved a blip onto a conversation!');
nowjs.getGroup(nowRoomID).now.receiveMessage(nowUserName, message);
}
});
With MongoDB, if you don't explicitly set a document's _id value then the client driver will automatically set it to an ObjectId value. This is different from databases that might generate IDs on the server and need another query to retrieve it, like with SQL Server's scope_identity() or MySQL's last_insert_id().
This allows you to insert data asynchronously because don't need to wait for the server to return an _id value before you continue.
So, as shown is Peter's answer, the _id is available before the document is saved to the database.
I just get the id from the document passed to the callback, since save returns the saved document.
Check below url
http://mongodb.github.io/node-mongodb-native/markdown-docs/insert.html
you will find following code in given url
var document = {name:"David", title:"About MongoDB"};
collection.insert(document, {w: 1}, function(err, records){
console.log("Record added as "+records[0]._id);
});