Sails.js query on an associated value - javascript

I'm using Sails.js version 0.10.0-rc4. All models are using sails-mysql.
I'm trying to query a model which has an "one-to-many" association to another model (the query is happening on the "many" side).
It looks something like this:
Post.find()
.where({ category: category_id })
.populate("category")
.exec( ... )
This gives me an empty array back however when I leave out the .populate("category") I get the correct result set.
I know that I could leave .populate("category") out and then fetch each correlating Category object separately, but I'm wondering if there's a better solution to this problem.

It's not 100% clear what you're trying to do here. If your goal is to filter the categories that get populated on the Post, you can do:
Post.find()
.populate("category", {where: { category: category_id }})
.exec( ... )
If you want to only retrieve Posts with a certain category, you would do:
Category.findOne(category_id)
.populate("posts")
.exec(function(e, c) {console.log(c.posts);})

Original post was too soon
Following works for me (sails 0.12) with population:
Post.find({category: category_id})
.populate("category")
.exec( ... )
But I am still puzzled who to search in a subquery any other attribute than id..
Edit2: Seems like deep query is not yet supported: https://github.com/balderdashy/waterline/issues/266

Related

"Bulk" Updating with Postgres DB and JS/Knex/Express Question

I have an update endpoint that when an incoming (request) contains a site name that matches any site name in my job site's table, I change all those particular DB entries status to "Pending Transfer" and essentially clear their site location data.
I've been able to make this work with the following:
async function bulkUpdate(req, res){
const site = req.body.data;
const data = await knex('assets')
.whereRaw(`location ->> 'site' = '${site.physical_site_name}'`)
.update({
status: "Pending Transfer",
location: {
site: site.physical_site_name,
site_loc: { first_octet: site.first_octet, mdc: '', shelf: '', unit: ''} //remove IP address
},
//history: ''
}) //todo: update history as well
.returning('*')
.then((results) => results[0]);
res.status(200).json({ data });
}
I also want to update history (any action we ever take on an object like a job site is stored in a JSON object, basically used as an array.
As you can see, history is commented out, but as this function essentially "sweeps" over all job sites that match the criteria and makes the change, I would also like to "push" an entry onto the existing history column here as well. I've done this in other situations where I destructure the existing history data, and add the new entry, etc. But as we are "sweeping" over the data, I'm wondering if there is a way to just push this data onto that array without having to pull each individual's history data via destructuring?
The shape of an entry in history column is like so:
[{"action_date":"\"2022-09-06T22:41:10.232Z\"","action_taken":"Bulk Upload","action_by":"Davi","action_by_id":120,"action_comment":"Initial Upload","action_key":"PRtW2o3OoosRK9oiUUMnByM4V"}]
So ideally I would like to "push" a new object onto this array without having (or overwriting) the previous data.
I'm newer at this, so thank you for all the help.
I had to convert the column from json to jsonb type, but this did the trick (with the concat operator)...
history: knex.raw(`history || ?::jsonb`, JSON.stringify({ newObj: newObjData }))

In Firebase Firestore, I want to use orderBy twice. Do I need to create an index to speed up the query?

In Firebase Firestore, I want to use orderBy twice. Do I need to create an index to speed up the query?
For example:
Query query = fsDB.collection("users").document(currentUID).collection("received_messages")
.orderBy("messageSeen").orderBy("date");
There is no automatic Error message that shows up like when using ranges or "where".
Structure looks like:
received_messages
date: 01/02/99
messageSeen: true
from: keuajopdf315
Should I put an index on the collection "received messages" and the "messageSeen" and "date" fields to speed up the query?
When I try to run a query with two orderBy() clauses, I get an error:
The query requires an index. You can create it here: ...
After adding the index that is linked in the error message, I can then retrieve the documents ordered-by-state-then-by-index. See my working jsbin here: https://jsbin.com/rewujav/edit?js,console
docs.orderBy("state").orderBy("index").get().then(function(snapshot) {
snapshot.forEach((doc) => {
console.log(doc.id+": state="+doc.data().state+" index="+doc.data().index);
})
})

I am unable to retrieve data from my mongodb collection and show it to my html page [duplicate]

I have a publication that should return me all users matching an _id array. here it the query:
Meteor.users.find({
'_id': { $in: myArray}},{
'profile.name':1,
'profile.description':1,
'profile.picture':1,
'profile.website':1,
'profile.country':1}
);
When I run it in Robomongo (the mongo browser), it works. But my publication only returns undefined. when I console.log(myArray); in the publication, I get something like this ['FZ78Pr82JPz66Gc3p']. This is what I paste in my working Robomongo query.
Alternative question: how can I have a better feedback(log) from the Collection.find() result?
It looks like you are trying to specify fields in your find, which you can do like this:
var options = {
fields: {
'profile.name': 1,
'profile.description': 1,
'profile.picture': 1,
'profile.website': 1,
'profile.country': 1
}
};
Meteor.users.find({_id: {$in: myArray}}, options);
However, if this is being used in a publish function, I strongly recommend using only top-level fields like so:
Meteor.users.find({_id: {$in: myArray}}, {fields: {profile: 1}});
For more details on why, please see this question.
For your second question, you can view the documents returned by a cursor by calling fetch on it. For example:
console.log(Posts.find({_id: {$in: postIds}}).fetch());

VSTS query by WIQL does not return requested fields

I'm building a Widget in VSTS and I'm calling the queryByWiql() method from Work Item Tracking rest client.
The query I have is:
queryString = {
"query": "Select [Microsoft.VSTS.Scheduling.RemainingWork]
From WorkItems
Where [System.WorkItemType] = 'Task'
AND [System.State] <> 'Done'
order by [System.CreatedDate] desc"
};
But the result looks like this, where none of the work item actually contain the Remaining Work Information:
This is true for any fields I request; Title, State, Assigned To etc.
The fields I've requested will appear under columns. But none of the work items themvselves will have the information.
Why is this the case? And how can I fix it? Cheers
This is an expected behavior. Currently, there is no way to call the API to return the detailed work item information from a WIQL query directly. You need to get these information in two steps:
Get the ID of the work items from a WIQL which you have done.
Get these work items via Get a list of work items by ID. And you can specify the field to get at this step.
Instruction on WIQL Query page:
After executing a query, get the work items using the IDs that
are returned in the query results response. You can get up to 200 work
items at a time.

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