I am new to node (v0.10) stack.
I am trying to achieve the following:
I have (hopefully) multilingual articles in the latest MongoDB such as:
_id
...more fields...
text: [
{lang: 'en', title: 'some title', body: 'body', slug: 'slug'},
....
]
Everytime I display an article in specific language I query as follows:
var query = Model.findOne({'text.slug': slug});
query.exec(function(err, doc){
async.each(doc.text, function(item, callback){
if (item.lang == articleLang) {
//populate the article to display
}
});
res.render('view', {post:articleToDisplay});
});
Slug is unique for each language!
The problem I have is that mongo will return the whole doc with all subdocs and not just the subdoc I searched for. Now I have to choose to iterate over all subdocs and display the appropriate one on client side or use async.each on the server to get the subdoc I need and only send to the views that one. I am doing it with async on the server. Is that OK? Also async iterates asynchronously but node still waits for the whole loop to finish and then renders the view. Am I missing anything thinking that the user is actually blocked until the async.each finishes? I am still trying to wrap my head around this asynchronous execution. Is there a way I can possibly improve how I manage this code? It seems to be quite standard procedure with subdocs!
Thanks in advance for all your help.
To achieve what you want, you need to make use of the aggregation pipeline. Using a simple findOne() would not be of help,
since you would then have to redact sub documents in your code rather than allowing mongodb to do it. find() and findOne() return the whole document when
a document matches the search criteria.
In the aggregation pipleline you could use the $unwind and $match operators to achieve this.
$unwind:
Deconstructs an array field from the input documents to output a
document for each element. Each output document is the input document
with the value of the array field replaced by the element.
First unwind the document based on the text values array.
$match:
Filters the documents to pass only the documents that match the
specified condition(s) to the next pipeline stage.
Then use the $match operator to match the appropriate documents.
db.Model.aggregate([
{$unwind:"$text"},
{$match:{"text.slug":slug,"text.lang":articleLang}}
])
Doing this would return you only one document with its text field containing only one object. such as: (Note that the text field in the output is not an array)
{ "_id" : ... ,.., "text" : { "slug" : "slug", "lang" : "en" ,...} }
Related
my document schema goes like this
_id: kkj33h2kjkjh32jk34
events: [
{
_id: k234j3lk4k2j3h4j3j4
},
{
_id: k234j3lk4k2j3h4j3j4
},
{
_id: k234j3lk4k2j3h4j3j4
}
]
here is my query, I have a list of _ids of the subdocuments of events field and I need to get all the matched subdocuments as the response from the event field I have tried to use $in and many but failed can anyone suggest me how to do this
tried this
subarr=['fh576hgfu658uyg7h','k234j3lk4k2j3h4j3j4']
model.findOne({
clgid: req.query.clgid,
'events._id': {$in:subarr}
},{"events.$":1});
but the problem with the above code is that it is fetching the first matching subdocument. but I need all the matching subdocuments.
suggest me the right way to do this query so that I get all the matched subdocuments that match from array
The issue of your query matching only the first subdocument is the use of {"events.$":1} in your projection.
I'm not sure what you are actually intending to do.
{"events.$":1} will limit to the first (sub)document matching your query, as per the documentation of the $ operator.
Maybe you're trying only to get the _id of the subdocuments and then, please try the following:
subarr=['fh576hgfu658uyg7h','k234j3lk4k2j3h4j3j4']
model.findOne({
clgid: req.query.clgid,
'events._id': {$in:subarr}
},{"events._id":1});
I'm having issues with mongoose queries.
I am trying to check if a object with an Id is in an array of objects.
So my query is like
db.getCollection('adunits').find(
{_id: ObjectId("5bd9bc1ca4efae39d0b5a58e")},
{$in : ["5bf510156c154934150ef006","5bf5309e6c154934150f00a6","5bd9b874a4efae39d0b5a58d","5bf52a876c154934150efe4a"]}
)
As you can see, my ObjectId("5bd9...") IS NOT in the array. But my query returns the document with ObjectId("5bd9...").
Isn't the $in operator supposed to check if the _id in parameter is IN the array?
I wish it could return me a "0 fetched documents" because the id passed isn't in the array.
Thanks in advance
Your query is not right.
You can either find by id like so:
db.getCollection('adunits')
.find({_id: ObjectId("5bd9bc1ca4efae39d0b5a58e")})
to get a single document or use $in operator like so
db.getCollection('adunits')
.find({_id: { $in: ["5bf510156c154934150ef006","5bf5309e6c154934150f00a6",...]})
which will return documents which have one of the ids provided in the array.
You query condition finds adunits where _id = ObjectId("5bd9bc1ca4efae39d0b5a58e"), it returns the value that matches given condition. While $in operator should applied on a filed. Are you trying to achieve some thing like, find the documents that matches ids in given array.if yes , change your code to following. Visit mongodb official https://docs.mongodb.com/manual/reference/operator/query/in/.
db.getCollection('adunits').find(
{ "_id":
{ $in:
[ "5bf510156c154934150ef006",
"5bf5309e6c154934150f00a6",
"5bd9b874a4efae39d0b5a58d",
"5bf52a876c154934150efe4a"
]
}
});
I need to get data from MongoDB that is first narrowed by one initial category, say '{clothing : pants}' and then a subsequent search for pants of a specific size, using an array like sizes = ['s','lg','6', '12'].
I need to return all of the results where 'pants' matches those 'sizes'.
I've started a search with:
Product.find({$and:[{categories:req.body.category, size:{$in:req.body.sizes}}]},
function(err, products) {
if (err) { console.log(err); }
return res.send(products)
});
I really don't know where to go from there. I've been all over the Mongoose docs.
Some direction would be very helpful.
The mongoose queries can receive object like Mongodb would. So you can pass the search parameters separated by ,
Product.find({categories:req.body.category, size:{$in:['s','lg','6', '12']}})
For more information on $in, check here
For more information on $and operator, check here (note we can ommit the $and operator in some cases and that is what I did)
I'm trying to get a list of books with their author information.
Some users were deleted and therefore they have not longer a document in the db, therefore, their info is null.
I'm trying to pull books ONLY if their creators still exist.
This is my code:
Book.find({_creator:{$ne:null}}).populate(
{
path: '_creator',
match: { _id: { $ne: null }}
})
.exec(function (err,books) {
if(err) throw err;
if(books) {
res.send(books)
}
})
This is what it returns:
[
{
"_id":"55d98e6a4de71010099c59eb",
"dateOfCreation":"2015-08-23T09:12:10.095Z",
"_creator":null,
"__v":0,
"coverUrl":"cover14403211323926quv.png",
"description":"asdasd",
"name":"asdasd"
}
]
Notice that the _creator field IS null.
Why is that?
you need to understand the order of execution of your code:
mongoose gets all books from the database where {_creator:{$ne:null}}. Mongo is only looking at the reference inside the books collection to determine which documents to return. Your book still has a reference to an author, and mongo will not notice that there is no matching Author in the Authors collection, so your book is loaded.
mongoose is populating all returned results: so it is loading the authors from the Authors collection and replaces the references with the real objects. For your book it does not find a matching author, so it puts the null there.
Thats why you end up with your resultlist.
Mongo does not support joins - therefore you cannot do a query that includes data from more than one collection. Populate is just a way to replace references in your resultlist with real data, you can never use populated data as part of your where clauses.
To solve your issue you can either:
filter your final resultlist in JS code, e.g. with _.filter of the lodash library.
update all your books and remove the reference whenever you delete an author. You can use hooks on the Author-Schema to do this.
AuthorSchema.post('remove', function(doc) {// update your books here});
I have two document
image document:
{_id:123,user:{user_sub_docuemnt},thumb:'dqwdqwdqwdw'}
post document:
{_id:444,
user:{user_sub_document},
attach:[{_id:123,
user:{user_sub_docuemnt},
thumb:'dqwdqwdqwdw'}
]
}
the user_sub_document contain password field, so I need to exclude that field.
This is what i have so far:
Post.aggregate([
{$match: {'user._id': {$in:idArr}}},
{$project:{content:1,attach:1,pub_date:1,'user.avatar':1}},
],function(err,posts){
if(err){
throw err
}else{
res.send(posts)
}
})
this will only limit user in Post level, there is another user_sub_document in attach array,so I tried this
{$project:{content:1,attach:1,'attach.user':0,pub_date:1,'user.avatar':1}},
this will give me an error The top-level _id field is the only field currently supported for exclusion
please help me with this!
You can achieve this with a simple find() statement:
Post.find({"user._id":{$in:idArr}},
{"content":1,
"user.avatar":1,
"pub_date":1,
"attach.user.avatar":1})
In case you choose to aggregate for some reason, You could modify your aggregation pipeline as below:
$match the records with specific user Ids.
$project only the required fields.
code:
Post.aggregate([
{$match:{"user._id":{$in:idArr}}},
{$project:{"user.avatar":1,
"attach.user.avatar":1,
"pub_date":1,
"content":1}}],function(err,resp){
// handle response
})