Meteor.js - Publish function not working: Coffeescript - coffeescript

I am having some trouble making the publish function work with Meteor. The code I am using is as follows:
Meteor.publish "adminArea", () ->
Meteor.users.find({
admin: true
}, {
fields: {
permissions: 1
}
})
and I am subscribing with:
Meteor.subscribe "adminArea"
This doesn't work though, when I run Meteor.user() in the console it just returns the default options.
If I run db.users.find({"admin": "true"}) in Mongo the correct information is returned.
The annoying thing is, this used to work perfectly until I reset my database with Meteor reset. Would this be messing it up or does anyone know what I am doing wrong now?
Thanks for any help.

I have now fixed this issue and it was complete error on my part. I had forgot to add the permissions field to the user in the database so when it ran the query, it would find admin: true but then be unable to return the permissions field because it didn't exist.
So note to self: Always add the necessary fields to the user.
Oops!
Thanks

Related

Wagtail 3.x postgres search returns no results

I recently updated from Wagtail 2.13.5 to 3.0.3. After the update, the search() method on Wagtail's PageQuerySet returns no results for search terms that clearly should return results (and which do when using the older version).
For example, under 2.13, where search_backend is an instance of wagtail.contrib.postgres_search.backend.PostgresSearchBackend, and qs is an instance of wagtail.core.query.PageQuerySet the following returns lots of results:
search_backend.search('popular-search-term', qs, fields=None, operator=None, order_by_relevance=True, partial_match=True)
But under 3.0.3, where search_backend is now an instance of wagtail.search.backends.database.postgres.postgres.PostgresSearchBackend and qs is an instance of wagtail.query.PageQuerySet, the same call to search() will return nothing (an empty queryset).
The data in the qs queryset is the same in both cases, so maybe I'm missing something in my configuration of the search backend? My "settings.py" file has:
WAGTAILSEARCH_BACKENDS = {
'default': {
'BACKEND': 'wagtail.search.backends.database',
'SEARCH_CONFIG': 'english',
},
}
and
INSTALLED_APPS = [
...
'wagtail.search',
'wagtail.search.backends.database.postgres',
...
]
I had to guess at the value for 'wagtail.search.backends.database.postgres'. AFAICT, Wagtail's docs don't mention what should go into INSTALLED_APPS. But the pre-upgrade value of 'wagtail.contrib.postgres_search' would clearly be wrong, as that module has been removed.
Anyone got an idea why calling search() on a PageQuerySet would incorrectly return no results?
The steps for changing the search backend are documented at https://docs.wagtail.org/en/stable/releases/2.15.html#database-search-backends-replaced. In particular:
You should remove wagtail.contrib.postgres_search from INSTALLED_APPS, and do not need to add anything in its place - the existing wagtail.search app is sufficient
After changing over, you need to re-run the ./manage.py update_index command to ensure that the new search index is populated.

E11000 duplicate key error collection {info.subs: null}

My app isn't letting me create more than one profile for some reason. Here's the setup in the service file:
//This finds the profile if it exists
async getProfile(user) {
let profile = await dbContext.Profile.findOne({
email: user.email
});
profile = await createProfileIfNeeded(profile, user);
await mergeSubsIfNeeded(profile, user);
return profile;
}
//This is supposed to create one if one doesn't exist
async function createProfileIfNeeded(profile, user) {
if (!profile) {
profile = await dbContext.Profile.create({
...user,
subs: [user.sub]
});
}
return profile;
}
It works for the first user, but when I make another, I get the error:
{"error":{"message":"MongoError: E11000 duplicate key error collection: TownMiner.profiles index: info.subs_1 dup key: { info.subs: null }","status":400},"url":"/api/profile"}
What's confusing is that subs are set via Auth0. When I look at it with a break-point in the server, it shows all the info there. Also, when I look in my MongoDB collections, nowhere does it say that any of the values are "null". I've used this same setup for a few projects now and they've all worked perfectly (and this new project is cloned from the same template). Also noted to make sure that the sub info is all different and it is.
This is the MongoDB collection:
_id: ObjectId("***")
subs:Array
0:"auth0|***dda6a"
1:"auth0|***aa288
name:"kevin#test.com"
picture:"https://s.gravatar.com/avatar/c6788456e2639d2d10823298cc219aaf?s=480&r..."
email:"kevin#test.com"
createdAt:2020-08-07T21:23:05.867+00:00
updatedAt:2020-08-17T17:24:05.583+00:00
__v:1
I've looked at the other answers for similar questions on here but couldn't quite find where it fit into this project. Any help would be great. Thanks!
There is a unique index in the TownMiner.profiles collection on {info.subs:1}.
That sample document doesn't include an info field, so the value entered in the index for that document would be null.
Since the index is tagged unique, the mongod will not permit you to insert any other document that would also be entered into the info.subs index using null.
Turns out the error was because I went on the mongoDB site and manually added a collection and probably set it up wrong. I deleted it and let my app build the collection itself and it seems to be working fine. Thank you for taking time to help! Always appreciated!

Meteor.subscribe on server side

I want to create a backend service which monitors a mongodb collection for new entries. As those are being created, I wish to run processing and update them.
I thought doing so with a Meteor service/app would be a wise idea because Meteor uses 'oplog tailing' which seems ideal for this purpose (I'd rather avoid polling if possible).
As such, I figured creating a minimal server-side-only app should solve it.
So basically, I need something along these lines:
if (Meteor.isServer) {
MyCollection = new Mongo.Collection('myCollection');
Meteor.publish('myCollectionPub', function () {
return MyCollection.find({ some: criteria... });
}
// is there such a thing?
Meteor.serverSideSubscribe('MyCollectionPub',
function (newDocs) {
// process/update newDocs
});
}
According to the Meteor docs, I cannot use Meteor.subscribe() on the server (and indeed it crashes if I try).
Question is:
Are there ways of 'subscribing' to collection updates on the server?
The PeerLibrary server-autorun package (along with it's dependant, reactive-mongo) will provide you with easy server-side observation of collections.
An alternative to #tarmes suggestion is the collection-hooks package, however as pointed out by David Weldon, it will only trigger in instance it is run in:
https://github.com/matb33/meteor-collection-hooks
MyCollection.after.insert(function (userId, doc) {
// ...
});
If you need it to run even when another instance makes a change in the mongo database, you can observe a cursor that is returned from your collection:
MyCollection.find({created_at : {$gt: some_current_time}}).observe({
added: function(item) {
// Alert code
}
});

sails.models.['CollectionName'] is not working in latest Sails Version

I am trying to access Model component via sails.models.['CollectionName'] as these CollectionName will be dynamically sent into this piece of functionality. But it is throwing undefined error.
/sails12.rc3/myapps/api/services/UserService.js:86
var findQuery = sails.models['User'].find({id: inputID
^
/sails12.rc3/myapps/api/services/UserService.js:86
var findQuery = sails.config.models['User'].find({id: inputID
^
/sails12.rc3/myapps/api/services/UserService.js:86
var findQuery = sails.config.models['user'].find({id: inputID
^
TypeError: Cannot read property 'find' of undefined
at Object.UserService.formNewData
(/sails12.rc3/myapps/api/services/UserService.js:86:52)
at Object.bound [as formNewData] (/usr/local/lib/node_modules/sails/node_modules/lodash/dist/lodash.js:729:21)
at /sails12.rc3/myapps/api/services/UserInfoService.js:330:37
at fn (/usr/local/lib/node_modules/sails/node_modules/async/lib/async.js:638:34)
at Immediate._onImmediate (/usr/local/lib/node_modules/sails/node_modules/async/lib/async.js:554:34)
at processImmediate [as _immediateCallback] (timers.js:358:17)
Please note that sails.config is working perfectly fine..
I am using SailsJS 12 rc 3. ( I mean the latest Version at this time ).
Can you please suggest me about the troubleshooting in this regard.
Update 1:
Hi Jason,
In all 3 cases, the same errror.
I could technically confirm that you are right on
http://sailsjs.org/documentation/reference/configuration/sails-config-models
Still, I am not sure, if there are any update requires in
http://sailsjs.org/documentation/anatomy/my-app/config/models-js
currently in config/models.js,
module.exports.models = {
connection: 'mongoDB',
migrate: 'alter'
}
Please suggest if I need to update any config values in this models.js file?
Update 2
https://github.com/balderdashy/sails/blob/master/lib/hooks/orm/build-orm.js
I could see the following values for these global values
sails.config.models { connection: 'mongoDB', migrate: 'alter' }
sails.config.globals { adapters: true, models: true, services: true }
sails.config.globals.models true
And hence mine is not working..Please suggest some options.
Update 3
Thanks Travis. sails.models['user'].find is working fine without no change in the SailsJS version. So, let me test some more time.
Ps: Not sure, why i am unable to add a comment directly below ( MAC / chrome browser) . So, for now, editing this question itself.
I think you're accessing it incorrectly.
Try: sails.config.models['User']
Try converting the model name to lowercase.
sails.models['CollectionName'] will not work, because within the models object, the collection names are all lowercase.
sails.model['collectionname'] should work.
I'm not sure why this is, but I think it will be something in the building of the ORM in waterline.
edit : I think this happens here

meteor: database is undefined

I'm having some troubles understanding, what i believe is trivial but i can't seem to get my head around it.
I have this publish function in server.js (server only)
Meteor.publish("tikiMainFind", function(){
return tikiDB.find()
})
In app.js (server + client) i'm declaring this mongo collection:
tikiDB = new Mongo.Collection("tiki")
Why is it that this doesn't work in client.js
console.log(tikiDB.find())
//ReferenceError: tikiDB is not defined
Without any idea how you have your app structured, I agree with David Weldon's answer. Check File Load Order to see what order your files are getting loaded.