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
Related
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
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'}])
Im working on some sort of social network in which people are able to make posts about a topic and like them.
Im having trouble tracking user likes.
The schema is the following:
Users:
{ userId: "someId", likes: ["idPost1", "idPost4", ...] }
Posts:
{ postId: "someId", topic: "idTopic", postContent: "someContent"}
I need a query that can:
Take all posts from a certain topic, like this:
r.table('posts').filter({
topic: idTopic
}).run().then( posts => res.json(posts))
Look up to see if the current user (given by the user id) has liked any of the posts on that specific topic. Then return a JSON with all posts on that topic, and those liked by the user with "liked: true".
Im having trouble with step 2,
Please let me know if im modelling data the wrong way, or if you can think of any way I can accomplish step 2.
Thanks!
This function does what you're looking for in javascript. (Tested using the Data Explorer)
r.db("test").table('posts').filter({ topic: "idTopic" }).merge(function(post){
return {liked: r.table('users').filter({userId: "someId"})(0)('likes').contains(post("postId")) }; })
The merge function basically iterates every post and adds the field liked to it. The contains function checks whether the posts id is in the likes array and return in directly as truth value.
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!)
I am working on photo sharing application that has a mongodb model that looks a bit like:
Location = { _id : id, address : address, name : name }
Photo = {
_id: id,
_upvotes : [{ ref to User }],
_location : {ref to Location},
url: url,
selected : boolean
}
A quick overview of the code that I want to modify (nodejs/expressjs/mongoose):
Photo.find({})
.populate('_location')
.stream({ objectMode : true })
.pipe(res);//res being response stream in express.js
Is there a way to query on Photo model in such a way that:
If there is no Photo.selected in a Location
Then find the photo with maximum votes, by counting the length of upvotes
I did a deep research using MongoDBs mapReduce implementation, agregation framework, and $where operator, but did not find my way out.
If there is any other question, or reference that may lead to an answer, or a specific approach to follow, please let me know.