Find after populate mongoose - javascript

I'm having some trouble querying a document by values matching inside the document after population by mongoose.
My schemas are something like this:
var EmailSchema = new mongoose.Schema({
type: String
});
var UserSchema = new mongoose.Schema({
name: String,
email: [{type:Schema.Types.ObjectId, ref:'Email'}]
});
I would like to have all users which have a email with the type = "Gmail" for example.
The following query returns empty results:
Users.find({'email.type':'Gmail').populate('email').exec( function(err, users)
{
res.json(users);
});
I have had to resort to filtering the results in JS like this:
users = users.filter(function(user)
{
for (var index = 0; index < user.email.length; index++) {
var email = user.email[index];
if(email.type === "Gmail")
{
return true;
}
}
return false;
});
Is there any way to query something like this straight from mongoose?

#Jason Cust explained it pretty well already - in this situation often the best solution is to alter the schema to prevent querying Users by properties of documents stored in separate collection.
Here's the best solution I can think of that will not force you to do that, though (because you said in the comment that you can't).
Users.find().populate({
path: 'email',
match: {
type: 'Gmail'
}
}).exec(function(err, users) {
users = users.filter(function(user) {
return user.email; // return only users with email matching 'type: "Gmail"' query
});
});
What we're doing here is populating only emails matching additional query (match option in .populate() call) - otherwise email field in Users documents will be set to null.
All that's left is .filter on returned users array, like in your original question - only with much simpler, very generic check. As you can see - either the email is there or it isn't.

Mongoose's populate function doesn't execute directly in Mongo. Instead after the initial find query returns a set a documents, populate will create an array of individual find queries on the referenced collection to execute and then merge the results back into the original documents. So essentially your find query is attempting to use a property of the referenced document (which hasn't been fetched yet and therefore is undefined) to filter the original result set.
In this use case it seems more appropriate to store emails as a subdocument array rather than a separate collection to achieve what you want to do. Also, as a general document store design pattern this is one of the use cases that makes sense to store an array as a subdocument: limited size and very few modifications.
Updating your schema to:
var EmailSchema = new mongoose.Schema({
type: String
});
var UserSchema = new mongoose.Schema({
name: String,
email: [EmailSchema]
});
Then the following query should work:
Users.find({'email.type':'Gmail').exec(function(err, users) {
res.json(users);
});

I couldn't find any other solution other than using Aggregate. It will be more troublesome, but we will use Lookup.
{
$lookup:
{
from: <collection to join>,
localField: <field from the input documents>,
foreignField: <field from the documents of the "from" collection>,
as: <output array field>
}
}

Related

Add a new field in mongoDB from another collection independently?

I have two collections: profiles and contents
The profiles collection looks like this:
{
_id: ObjectId('618ef65e5295ba3132c11111'),
blacklist: [ObjectId('618ef65e5295ba3132c33333'), ObjectId('618ef65e5295ba3132c22222')],
//more fields
}
The contents collection looks like this:
{
_id: ObjectId('618ef65e5295ba3132c00000'),
owner: ObjectId('618ef65e5295ba3132c22222'),
//more fields
}
What I need is to get those contents where owner is not included in the blacklist. I thought about to put the blacklist field into the contents documents. I could get the profile by id separately (in another query) and set it manually in the aggregation where I get the contents, but this requires one extra connection.
So my question is: Is there a way to add my profile into each document of another collection? keep in mind that I have the profile ID.
Here is some psuedo code on how it "should" look like, First fetching the blacklists owners, then using that variable as a parameter in the pipeline.
const profileId = input;
const blackListIds = await db.getCollection('profiles').distinct('blacklist', { _id: profileId });
const aggregationResults = await db.getCollection('contents').aggregate([
{
$match: {
owner: {$nin: blackListIds}
}
}
... continuation of pipeline ...
])

How can I access a specific attribute of a specific document in a mongoDB collection?

To summarize, I am working with 2 collections - 'usercollection' and 'groupcollection' and I would like to associate users with groups. I don't want to have 2 copies of all the user documents so I have a unique ID attribute for each user that I want to use to associate specific users with specific groups. This is all running on a localhost webserver so I'm getting the input from an html page with a form in it where you enter 'username' and 'groupname'. I tried using the .distinct() function with query as 'username' and the target field/attribute as 'uid'.
// Set our internal DB variable
var db = req.db;
// Get our form values. These rely on the "name" attributes
var userName = req.body.username;
// Set query and options for searching usercollection
var query = {"username" : userName};
const fieldName = "uid";
// Set our collections
var users = db.get('usercollection');
// Get UID corresponding to username
var uidToAdd = users.distinct(fieldName, query);
This is what I attempted (with some other lines that aren't relevant taken out) but it just returned a null object so I'm at a bit of a loss. Also, I'm still a beginner with nodejs/javascript/mongoDB so the more informative the answer the better! When I do the same code in the mongo shell I can get the actual value of the 'uid' attribute so I really don't know what's going wrong
I am not sure I am following you. But if I understood correctly, if you want to make a relationship between 'usercollection' and 'groupcolletion', you can simply create those 2 collections and each user in 'usercollection' should have a field with 'groupid' as a reference. In this way, you can access 'groupcollection' easily.
Here is an example with using mongoose.
In User model
...
groupId: {
type: mongoose.Schema.Types.ObjectID
ref: "Group"
}
...
Later you can also use 'populate' to fetch 'Group' information.
...
let data = await User.findById(id).populate('groupId');
...

Parse - limit result of a Query in Cloud Code

Hello is this code in the comment possible with Parse Cloud Code?
Parse.Cloud.beforeFind('Note', function(req) {
var query = req.query;
var user = req.user;
// if a given 'Note' visibility is set to 'Unlisted'
// return only the Notes with 'user' field that the calling _User
});
The documentation only shows how to filter fields that are returned but not exactly remove items from the query result in the Cloud Code.
This can be done through ACL, I know, but the caveat is that if the request is a retrieve function and not query the Note should still return.
Assuming you've saved the user as an object relationship (not a string id). Just add the qualification you need, such as:
query.equalTo("your_user_pointer_col_on_Note", user)

Two equalTo in parse.com javascript [duplicate]

I need to connect 2 queries in Parse.com with an and, my code is:
var queryDeseo1 = new Parse.Query(DeseosModel);
queryDeseo1.equalTo("User", Parse.User.current());
queryDeseo1.equalTo("Deseo", artist);
queryDeseo1.find({...
The result of the .find is all the objects with User = Parse.User.current()) and all the objects with Deseo = artist but I want the objects with the two queries together:
User = Parse.User.current()) and Deseo = artist
You've actually got it setup correctly to do an AND query. The problem (assuming that your data structure is setup properly) is that your User field is a Pointer to the User table. Therefore, you need to query for a User equal to the pointer, as opposed to a User equal to Parse.User.current() which will return a string. Something like the following:
var userPointer = {
__type: 'Pointer',
className: 'User',
objectId: Parse.User.current().id
}
queryDeseo1.equalTo('User', userPointer);

Update specific values in a nested array within mongo through mongoose

I have somewhat the following schema(without _id) -
{uid: String,
inbox:[{msgid:String, someval:String}]
}
Now, in the request I get the msgid and I use it in the following mongoose query like this-
my_model.findOne({'inbox.msgid':'msgidvaluexyz'}
, function(err, doc) {
console.log(doc);
return !0; })
Now, the problem is that I get the whole document which has the specific message along with the other messages in inbox -
Output-
{uid:'xyz',
inbox:[
{msgid:,someval},
{msgid:'our queried msgid',someval}, //required sub array
{msgid:,someval},
]
}
Now what query can i use to get the specific sub array only as the document inbox is too large to be looped through.
Use the $ positional selection operator to have the returned doc only include the matched inbox element:
my_model.findOne({'inbox.msgid':'msgidvaluexyz'}
, {'inbox.$': 1}
, function(err, doc) {
console.log(doc);
return !0; })
If I understood your question correctly:
// find each person with a last name matching 'Ghost'
var query = Person.findOne({ 'name.last': 'Ghost' });
// selecting the `name` and `occupation` fields
query.select('name occupation');
http://mongoosejs.com/docs/queries.html
You can select which fields you want to get back. You could get only the inbox array or everything except that.

Categories