nodejs Cycle and callback - javascript

Recently i wrote a blog with nodejs,when it comes to add some tags to posts,problems occured.In my view, the relation between posts and tags is many-to-many,each post has several tags,in turn,each tag also match to some posts.So i create a tag collection and a post collection in mongodb.
exports.Post=mongolass.model("Post",{
author:{type:Mongolass.Types.ObjectId,ref:"User"},
title:{type:"string"},
content:{type:"string"},
pv:{type:"number"},
tagIds:[{tagId::Mongolass.Types.ObjectId}]
});
exports.Tag=mongolass.model("Tag",{
tagName:{type:"string"}
});
exports.Tag.index({tagName:1},{unique:true}).exec();
and store the tag as an array in posts.As we know,when i create a post, i will get the post's tagName from html by method POST,so i have to use
getTagByName:function getTagByName(tagName){
return Tag.find({tagName:tagName}).exec();
}
to get the object tag,and use
TagModel.getTagByName(tagName).then(function(tag){
var postToTag={
postId:postId,
tagId:tag[0]._id
};
to get the tagId,Unfortunately, as a post has many tags,so i have to use a for cycle to get all tagId of a post, i also want to collect these tagIds to an Array, thus i can push it to my Post model, but the cycle and callback make it difficult.
any advice is appreciated.

Related

Restangular: getList(), then get related information

I am trying to wrap my head around how this would be done.
Get a list of "Creations".
"Creations" list returns an ID of the "Author" of that creation.
Automatically do another Restangular call to grab that Authors information and relate it to the object returned by the first getList of creations.
Restangular.all('creations').getList({
limit: 5
}).then(function(creations) {
$scope.creations = creations;
// returns a list of Objects for each creation with one parameter being author:id (author:1,2,3, etc)
// THEN GET INFORMATION ABOUT EACH CREATION'S AUTHOR
// Restangular.one('users', creations.author).get().......?
});
Is there a better way of doing this so that in my view I can access something like $scope.creations.authorObject...

Breeze EntityManager.executeQuery with expand - httpResponse data does not match result data?

I'm working on a web app that uses Breeze and Knockout. I have the following function:
function getArticle(id, articleObservable) {
var query = EntityQuery.from('KbArticles')
.where("articleId", "==", id)
.expand("KbArticleType, KbSubject, KbArticleTags");
return manager.executeQuery(query)
.then(querySucceeded)
.fail(queryFailed);
function querySucceeded(data) {
if (articleObservable) {
articleObservable(data.results[0]);
}
log('Retrieved [Article] from remote data source', data.results.length, true);
}
}
A 1 to many relationship exists between the KbArticles entity and the KbArticleTags entity. The goal of this function is to fetch a specific article and the list of tags associated with the article. The function executes successfully (and I DO get data for the other 2 expanded entities - they are 1 to 1), however, I get an empty array for the KbArticleTags in data.results. Interestingly, the tags are populated in data.httpResponse:
So, it appears that the data is coming over the wire, but it's not making it to the results in the querySucceeded function. I tried to step through the breeze code to determine how the httpResponse is mapped to the result, but got lost fairly quickly (I'm a javascript newb). Does anyone have any troubleshooting tips for figuring out why the expanded entity doesn't show in the results, but is returned in the httpResponse? Or am I trying to do something that isn't supported?
Ok, so for whatever reason (I probably deleted it one day while testing and didn't add it back), the navigation property (in my Entity Framework diagram) was missing on the KbArticleTag entity:
All I had to do was add that back and everything is working as expected.

Fetch Backbone Collection by Model IDs list

I have a REST API serving a few URLs:
/rest/messages
provides all messages. A message is a JSON/Backbone Model
{
title: 'foo',
body : 'bar'
}
To get a single message I have:
/rest/messages/:id
Is it possible to fetch a Backbone Collection using message IDs array? I don't want the whole message list, but just a few messages I specify by ID.
I could fetch Models one-by-one and fill up the Collection, but I'm wondering if Backbone has a cleaner way to do this.
Thanks
According to documentation, you can pass ajax options to the fetch call. So, you can pass ids as data attribute to the fetch call being done and based on it, return the respective models from the server.
For example (when doing fetch),
collection.fetch({
data : {
message_ids : [1, 3, 5] // array of the message ids you want to retrieve as models
}
})
This message_id array will be accessible as parameters (not sure of the name in your case) in the server code being executed at /rest/messages, from there you can return only specific models based on ids you receive as message_ids. The only thing you need is, client side must be aware of the ids of all the message models it needs.
You can use any data structure instead of array to send message_ids.
The url property of collection reference to the collection location on the server. When you use fetch, backbone uses that url.
The url property can be also a function that returns the url. So you can do something like that:
var ids = [1,2,3]
var messages = new MessegecCollection();
messages.url = function() {
return "/rest/messages/"+ids.join("-"); //results "/rest/messages/1-2-3"
}
messages.fetch();
You can also create a method in your collection that generated and set the url, or even fetchs a set of models.
Now all you have to do is to support this url: /rest/messages/1-2-3
Hope this helps!

How to exclude an object's id property before or during $.toJSON

I'm writing a custom REST adapter for ember-data users with a django rest framework app and need to build a JSON string to do POST/PUT. The only problem is I can't seem to chain another jQuery method after the $.toJSON that removes this.
So far I have an ember.js object that I plan to extract each property from, except my django app doesn't want the id to go along with the HTTP POST
I can get a legit string like so
$.param(record.toJSON());
This results in the following
id=0&username=dat
I'd like a quick way to exclude id when I do this toJSON (does this exist w/ out writing it by hand?) Using jQuery 1.8+
Thank you in advance
Turns out this was really simple
var json_data = record.toJSON();
delete json_data.id;
var data = $.param(json_data);
Now instead of
id=0&username=dat
I now get
username=dat

How do I get a model from a Backbone.js collection by its id?

In my app, everything I do with data is based on the primary key as the data is stored in the database. I would like to grab a model from a collection based on this key.
Using Collection.at() requires the array index, Collection.getByCid() requires the client ID that backbone randomly generates.
What is the best way to grab the model I want from the collection with the given id value? I figure the worst I could do would be to iterate over each item, .get('id'), and return that one.
Take a look at the get method, it may be of some help :)
http://backbonejs.org/#Collection-get
get collection.get(id)
Get a model from a collection, specified by an id, a cid, or by passing in a model.
If your data requires you to use a different kind of key or a set that doesn't mesh well with at(), getByCid() or get(), there is also where(). Something like this might work:
window.lib = new Library;
window.lib.fetch([
success: function(model, response) {
console.log(window.lib.where({'BookID':488, 'Rev':2, 'Status':'Active'});
}
});

Categories

Resources