Contentful JS API: Query for related articles with similar tags as the currently viewed article ? (article…tagList[]) - contentful

Overview:
Someone views an article (contenttype : article). This article has a list of tags (contenttype : articletags).
Based on the linked tags in this article, I am trying to do a query for articles which has one or more of the same tags linked to it (call it Related Articles with same tags).
Here is the structure:
let tags = article.items[0].fields.tagsList.map(tag => {
return tag.fields.navn
})
Which I need to query for articles like this:
contentful.getEntries({content_type: ‘article’}) ???
How can I query for the ids?

I think what you're looking for is the links_to query parameter.
With this one you can figure out which entries relate to another one.
client.getEntries({
links_to_entry: '<entry_id>'
})

You can use the [in] operator to query for entries with a given tag.
contentful
.getEntries({
content_type: "article",
'fields.tags': "website" , //tag id = website
})
.then(({ items }) => {
console.log(items);
})
.catch(console.error);
reference: https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/search-parameters/inclusion

Related

how to find data into an array mongodb , nodejs

I am finding data from an array. that is a course and I want to find out an article by using the title, which is stored into the Course's Articles. I am going step by step...
(1) I want fine the course by the name,
(2) after of it, I want to find an article into course's article by using the title of an article
(3) and render the article and course to the web page
here is code
const course = req.params.course
const article_title = req.query.article
Course.findOne({name: course , article:article_title}).then(function(data){
console.log(data)
res.render('article',{data :data})
}).catch((err)=>{console.log(err)});
here is DB
_id:61c057cfd70f2fb178d4e996
name:"Soft "
discription:"House"
article:Array
0:Object
title:"Where does it come from?"
content:"<p>Title is very important for an article to explain content | article..."
_id:61c05d4a3905f61f72a8e61b
1 :Object
2:Object
To search you can use:
Couse.findOne({name: course, 'article.title': article_title})
So you will get the document with the articles you need.
Using projection and $elemMatch, you can filter the article array itself so that only the subdocument you want is there:
Couse.findOne({name: course, 'article.title': article_title}, {
article: {
$elemMatch: {
title: article_title
}
}
})
You can try it in MongoPlayground
https://mongoplayground.net/p/SVXNGE6tuW7

Mongoose display comments and stars(likes) for each post [duplicate]

In Mongoose, I can use a query populate to populate additional fields after a query. I can also populate multiple paths, such as
Person.find({})
.populate('books movie', 'title pages director')
.exec()
However, this would generate a lookup on book gathering the fields for title, pages and director - and also a lookup on movie gathering the fields for title, pages and director as well. What I want is to get title and pages from books only, and director from movie. I could do something like this:
Person.find({})
.populate('books', 'title pages')
.populate('movie', 'director')
.exec()
which gives me the expected result and queries.
But is there any way to have the behavior of the second snippet using a similar "single line" syntax like the first snippet? The reason for that, is that I want to programmatically determine the arguments for the populate function and feed it in. I cannot do that for multiple populate calls.
After looking into the sourcecode of mongoose, I solved this with:
var populateQuery = [{path:'books', select:'title pages'}, {path:'movie', select:'director'}];
Person.find({})
.populate(populateQuery)
.execPopulate()
you can also do something like below:
{path:'user',select:['key1','key2']}
You achieve that by simply passing object or array of objects to populate() method.
const query = [
{
path:'books',
select:'title pages'
},
{
path:'movie',
select:'director'
}
];
const result = await Person.find().populate(query).lean();
Consider that lean() method is optional, it just returns raw json rather than mongoose object and makes code execution a little bit faster! Don't forget to make your function (callback) async!
This is how it's done based on the Mongoose JS documentation http://mongoosejs.com/docs/populate.html
Let's say you have a BookCollection schema which contains users and books
In order to perform a query and get all the BookCollections with its related users and books you would do this
models.BookCollection
.find({})
.populate('user')
.populate('books')
.lean()
.exec(function (err, bookcollection) {
if (err) return console.error(err);
try {
mongoose.connection.close();
res.render('viewbookcollection', { content: bookcollection});
} catch (e) {
console.log("errror getting bookcollection"+e);
}
//Your Schema must include path
let createdData =Person.create(dataYouWant)
await createdData.populate([{path:'books', select:'title pages'},{path:'movie', select:'director'}])

CouchDb get post author

My post document looks like the following:
{
_id: ...,
type: 'post',
title: ...,
description: ...,
author: 'user_id'
}
And another user document:
{
_id: 'user_id',
type: 'user',
name: ...,
}
How do I fetch the post and the linked user document given that I only know post id?
Having user document inside the post document doesn't seems like a good solution as if the user changes his/her name or other details, I will have to update every post.
Another solution would be to include a posts array in the user document and use two emits in the view document. But with frequent posts and high number of posts, this looks a little inefficient.
You mentioned "linked documents" as if you were referencing this feature in CouchDB, but it doesn't appear like you meant it that way.
It turns out, this is totally supported. Your document structure doesn't need to change at all, you can use a map function like this:
function (doc) {
if (doc.type === 'post') {
emit(doc._id)
emit(doc._id, { _id: doc.author })
}
}
By emitting an object with an _id property as the value, it allows CouchDB to look up a different document (in this case, the user document) than the original when you add include_docs=true on your view query. This allows you to fetch an entire collection of related documents in a single query! I'd reference the documentation I linked to earlier for a complete example. (the rest of their docs are great too!)

Fetch posts by category with bookshelf.js

I'm using bookshelf.js as my ORM for node. I have 2 models
Post = bookshelf.Model.extend({
tableName: 'posts',
categories: function () {
return this.belongsToMany('Category');
}
});
Category = bookshelf.Model.extend({
tableName: 'categories',
posts: function () {
return this.belongsToMany('Post');
}
});
They are related via categories_posts table, so its a many to many relationship.
Now I want the user to be able to view all posts in certain category. But I dont want just all posts, I want pagination. But I'm unable to fetch the total posts under specific category, it always returns the total posts that exists in the system.
I've tried this Category.forge({id: id}).posts().query().count('*').then(function(total) {}); but total equals the total posts in posts table as opposed to total posts under category identified by id. Is this even possible, or I should make a helper method that directly queries the categories_posts table?
Thanks.
Ok I think I found a solution.
Category.forge({id: id}).fetch({withRelated: [{posts: function(q) {
q.count('* AS count');
}}]})
.then(function(total) {
console.log(total.toJSON().posts[0].count);
});
Will give the correct value of posts under category identified by id.

Pulling links to all documents that have a column "XXXX" in sharepoint

I have a site collection in which there are lot of sites, and each site has a number of documents which are tagged as "XXX" in a particular column. Now, if I have to pull links to all documents in the site collection that are tagged "XXX" and display them in a list, how do I go about it? I mean how do I start it?
Do you have any knowledge with JavaScript ? Because you could use it to do this kind of task...
For example with SPServices you can get all the sites:
$().SPServices({
operation: "GetAllSubWebCollection",
completefunc: function(xData, Status) {
$(xData.responseXML).find("Webs > Web").each(function() {
var $node = $(this);
getDocuments( $node.attr("Title") );
});
}
});
Then with SharepointPlus (because the syntax is easier but you can still use SPServices) you can get the documents:
function getDocuments(site) {
$SP().list("My Document List", site).get({fields:"Title",where:"My_x0020_Column = 'XXX'"}, function(data) {
for (var i=data.length; i--;) console.log(data[i].getAttribute("Title"))
})
}
Of course at this point, instead of console.log you should inject the link into your webpage.
It's just a very basic example of what you could do.

Resources