Iron router routes from db - mongodb

I try to load my routes from db. My collection schema for routes is:
AsideMenu.attachSchema(
new SimpleSchema({
name: {
type: String,
denyUpdate: true
},
path: {
type: String,
denyUpdate: true
},
controller: {
type: String,
denyUpdate: true
}
})
);
I defined also a method for publish and subscribe and everything works well, i can get on client all the records on which he has access, but i cant get the router to register them.
_.map(menuRoutes, function (route) {
Router.route(route.path,
{
name: route.name,
controller: route.controller,
})
})
When I access in client console:
console.log(Router.routes) I get []
And if i print it in server console i get all routes:
I20150227-19:02:47.753(2)? { [Function]
I20150227-19:02:47.753(2)? getName: [Function],
I20150227-19:02:47.753(2)? findControllerConstructor: [Function],
I20150227-19:02:47.754(2)? createController: [Function],
I20150227-19:02:47.754(2)? setControllerParams: [Function],
I20150227-19:02:47.754(2)? dispatch: [Function],
I20150227-19:02:47.754(2)? path: [Function],
I20150227-19:02:47.754(2)? url: [Function],
I20150227-19:02:47.755(2)? params: [Function],
I20150227-19:02:47.755(2)? get: [Function],
I20150227-19:02:47.755(2)? post: [Function],
I20150227-19:02:47.755(2)? put: [Function],
I20150227-19:02:47.755(2)? delete: [Function],
I20150227-19:02:47.756(2)? options:
I20150227-19:02:47.756(2)? { name: 'calendar.index',
I20150227-19:02:47.756(2)? controller: 'CalendarController',
I20150227-19:02:47.756(2)? data: [Function],
I20150227-19:02:47.756(2)? mount: false },
I20150227-19:02:47.757(2)? _actionStack: { _stack: [], length: 0 },
I20150227-19:02:47.757(2)? _beforeStack: { _stack: [], length: 0 },
I20150227-19:02:47.757(2)? _afterStack: { _stack: [], length: 0 },
I20150227-19:02:47.757(2)? _methods: {},
I20150227-19:02:47.758(2)? _path: '/calendar',
I20150227-19:02:47.758(2)? handler:
I20150227-19:02:47.758(2)? { options: [Object],
I20150227-19:02:47.758(2)? mount: false,
I20150227-19:02:47.758(2)? method: false,
I20150227-19:02:47.759(2)? where: 'client',
I20150227-19:02:47.759(2)? name: 'calendar.index',
I20150227-19:02:47.759(2)? path: '/calendar',
I20150227-19:02:47.759(2)? compiledUrl: [Object],
I20150227-19:02:47.759(2)? handle: [Circular],
I20150227-19:02:47.917(2)? route: [Circular] },
I want to know if this is possible because i couldnt find any example with this aproach.

Yes, this should be possible. I have a similar setup working just fine, the only difference being that I create the routes from a static array, not a db query. But that should make a difference.
This works for me, when executed during load:
_.each(routes, function(foo, route) {
Router.map(function () {
this.route(route, {
path: route,
action: function() { ... }
});
});
});
Where/when are you executing the _.map code you showed?

Iron router runs a reactive computation, but at the time your subscription to your route definitions collection is not ready. So if you put that block in your ready callback which is:
Meteor.subscribe('router-data-publication', function() {
/* construct your routes here*/
});
or, you can do something safer, but essentially the same, using a handle within a Tracker and checking .ready() on the handler.

Related

Why is mongoDB aggregation $count method gives an object of AggregationCursor as result using node.js and promise?

I am trying to get count of an array in a document by using Mongodb aggregation $count operator.
I am using node.js and promise for this. Here is my code:
getDaysPresent:(id)=>{
return new Promise(async(resolve,reject)=>{
let days=await db.get().collection(collection.'student_collection').aggregate([
{
$match:{_id:ObjectId(id)}
},{
$unwind:"$attendance"
},{
$count:"attendance"
}
])
resolve(days)
})
}
When I try this Mongo Db code in Robo3T it gives the key and value object properly. But when code
executed the console of days gives a AggregationCursor objects with the below details:
AggregationCursor {
_readableState: ReadableState {
objectMode: true,
highWaterMark: 16,
buffer: BufferList { head: null, tail: null, length: 0 },
length: 0,
pipes: null,
pipesCount: 0,
flowing: null,
ended: false,
endEmitted: false,
reading: false,
sync: true,
needReadable: false,
emittedReadable: false,
readableListening: false,
resumeScheduled: false,
emitClose: true,
autoDestroy: false,
destroyed: false,
defaultEncoding: 'utf8',
awaitDrainWriters: null,
multiAwaitDrain: false,
readingMore: false,
decoder: null,
encoding: null,
[Symbol(kPaused)]: null
},
readable: true,
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
operation: AggregateOperation {
options: { readPreference: [ReadPreference] },
ns: MongoDBNamespace { db: 'classroom', collection: '$cmd' },
readPreference: ReadPreference {
mode: 'primary',
tags: undefined,
hedge: undefined
},
readConcern: undefined,
writeConcern: undefined,
explain: false,
fullResponse: true,
target: 'student',
pipeline: [ [Object], [Object], [Object] ],
hasWriteStage: false,
cursorState: {
cursorId: null,
cmd: {},
documents: [],
cursorIndex: 0,
dead: false,
killed: false,
init: false,
notified: false,
limit: 0,
skip: 0,
batchSize: 1000,
currentLimit: 0,
transforms: undefined,
raw: undefined,
reconnect: true
}
},
pool: null,
server: null,
disconnectHandler: undefined,
bson: undefined,
ns: 'classroom.$cmd',
namespace: MongoDBNamespace { db: 'classroom', collection: '$cmd' },
cmd: {},
options: {
readPreference: ReadPreference {
mode: 'primary',
tags: undefined,
hedge: undefined
}
},
topology: Server {
_events: [Object: null prototype] {
commandStarted: [Function],
commandSucceeded: [Function],
commandFailed: [Function],
serverOpening: [Function],
serverClosed: [Function],
serverDescriptionChanged: [Function],
serverHeartbeatStarted: [Function],
serverHeartbeatSucceeded: [Function],
serverHeartbeatFailed: [Function],
topologyOpening: [Function],
topologyClosed: [Function],
topologyDescriptionChanged: [Function],
joined: [Function],
left: [Function],
ping: [Function],
ha: [Function],
connectionPoolCreated: [Function],
connectionPoolClosed: [Function],
connectionCreated: [Function],
connectionReady: [Function],
connectionClosed: [Function],
connectionCheckOutStarted: [Function],
connectionCheckOutFailed: [Function],
connectionCheckedOut: [Function],
connectionCheckedIn: [Function],
connectionPoolCleared: [Function],
authenticated: [Function],
error: [Array],
timeout: [Array],
close: [Array],
parseError: [Array],
open: [Array],
fullsetup: [Array],
all: [Array],
reconnect: [Array]
},
_eventsCount: 35,
_maxListeners: Infinity,
s: {
coreTopology: [Server],
sCapabilities: [ServerCapabilities],
clonedOptions: [Object],
reconnect: true,
emitError: true,
poolSize: 5,
storeOptions: [Object],
store: [Store],
host: 'localhost',
port: 27017,
options: [Object],
sessionPool: [ServerSessionPool],
sessions: Set {},
promiseLibrary: [Function: Promise]
},
[Symbol(kCapture)]: false
},
cursorState: {
cursorId: null,
cmd: {},
documents: [],
cursorIndex: 0,
dead: false,
killed: false,
init: false,
notified: false,
limit: 0,
skip: 0,
batchSize: 1000,
currentLimit: 0,
transforms: undefined,
raw: undefined,
reconnect: true
},
logger: Logger { className: 'Cursor' },
s: {
numberOfRetries: 5,
tailableRetryInterval: 500,
currentNumberOfRetries: 5,
state: 0,
promiseLibrary: [Function: Promise],
explicitlyIgnoreSession: false
},
[Symbol(kCapture)]: false
}
My sample document as follow:
{
"_id" : ObjectId("5fd6fa3b4150e552f0b75935"),
"Name" : "Bobby",
"Gender" : "Male",
"RollNo" : "1",
"attendance" : [
"2/1/2021",
"3/1/2021",
"4/1/2021"
]
}
IF you guys know about this please let me know. And by the by this is my first question in stackoverflow so please give me suggestions to improve this question. Thank you
You could use $size operator to compute the length of an array field in the document. Please modify to suit the programming language and driver.
db.user.aggregate([
{
$project: {
length: {
$size: "$attendance"
}
}
}
])
https://mongoplayground.net/p/UbQh1feZaF0
I got the $count properly, when I add toArray() to the end of aggregation method. The count object will be in an array.
getPresentDays:(id)=>{
return new Promise(async(resolve,reject)=>{
var days=await db.get().collection(collection.STUDENT_COLLECTION).aggregate([
{
$match:{_id:ObjectId(id)}
},{
$unwind:"$attendance"
},{
$count:"attendance"
}
]).toArray()
resolve(days[0].attendance)
})
}

Nuxt.js socket hang up on axios get only on https not http server

I'm using Nuxt 2.8.1, Axios Module (https://axios.nuxtjs.org).
I followed up this guide https://nuxtjs.org/faq/http-proxy/ to solve CORS problems on Firefox/IE, but ended up NuxtServerError: socket hang up on every proxied request if I ENABLE server https option in nuxt.config.js, not if I disable.
I tried adding rejectUnauthorized: false to server https param, wrote an express server to handle the SSL certificate and render using Nuxt,... but still can't solve the problem.
This is my nuxt.config.js:
env: {
API_HOST: 'https://api.mywebsite.com',
BASE_URL: process.env.BASE_URL || 'http://localhost:3000',
},
axios: {
proxy: true,
},
proxy: {
'/api/': {
target: 'https://api.mywebsite.com/api',
pathRewrite: {'/api': ''},
credentials: false,
}
},
server: {
port: 3000,
https: {
rejectUnauthorized: false,
key: fs.readFileSync('../privkey.pem'),
cert: fs.readFileSync('../fullchain.pem')
}
}
It works well if i just remove whole https param in 'server'. Here is my axios call on store/index.js:
export const actions = {
async nuxtServerInit ( { commit } ) {
const { data } = await this.$axios.get('/api/option');
let options = {};
data.forEach(item => {
options[item.Name] = item.Value;
});
commit('setOptions', options)
},
}
This is my console log on that axios call:
Promise { 18:04:38
<rejected> [Error: socket hang up] {
at createHangUpError (_http_client.js:323:15)
at Socket.socketOnEnd (_http_client.js:426:23)
at Socket.emit (events.js:203:15)
at Socket.EventEmitter.emit (domain.js:448:20)
at endReadableNT (_stream_readable.js:1129:12)
at process._tickCallback (internal/process/next_tick.js:63:19)
code: 'ECONNRESET',
config: {
url: 'http://localhost:3000/api/option',
method: 'get',
headers: [Object],
baseURL: 'http://localhost:3000/',
transformRequest: [Array],
transformResponse: [Array],
timeout: 0,
adapter: [Function: httpAdapter],
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
validateStatus: [Function: validateStatus],
data: undefined
},
request: Writable {
_writableState: [WritableState],
writable: true,
domain: null,
_events: [Object],
_eventsCount: 2,
_maxListeners: undefined,
_options: [Object],
_redirectCount: 0,
_redirects: [],
_requestBodyLength: 0,
_requestBodyBuffers: [],
_onNativeResponse: [Function],
_currentRequest: [ClientRequest],
_currentUrl: 'http://localhost:3000/api/option'
},
response: undefined,
isAxiosError: true,
toJSON: [Function]
}
}
I would appreciate any help :)
I tried to use as many options as I thought was relevant in the proxy module, but ended up nowhere. I think you should create an issue on either #nuxtjs/proxy or on http-proxy-middleware github.
On my end the proxy route works without a problem with Vue's normal lifecycles, but will end up with a socket hang up when placed in asyncData or fetch - so I assume it's a SSR issue.
I don't have any problems with CORS, so I ended up creating module clones of the axios-module with custom prototypes. This setup unfortunately doesn't work alongside the axios-module as that also creates a socket hangup regardless of whether I have a proxy setup.
https://stackoverflow.com/a/43439886/1989083
I fixed my same issue by adding these lines into axios.js:
delete process.env['http_proxy'];
delete process.env['HTTP_PROXY'];
delete process.env['https_proxy'];
delete process.env['HTTPS_PROXY'];

Why mongoose's find() gives this weird result, with array of objects [duplicate]

This question already has answers here:
mongoose .find() method returns object with unwanted properties
(5 answers)
How can I display a JavaScript object?
(40 answers)
Closed 4 years ago.
I made a simple find query for mongoose, and it returns the result as well but it gives result in array of objects(this is not a problem), but it have array of objects, with objects contains its internal functions and properties, which I think not relevant to my need, as I only want the query result from database.
const Joi = require('joi');
const Session = require('../models/session.model');
exports.tokenUtility = async (req, res, next) => {
const {token, contactNumber, query} = req.body;
if(token) {
try{
const session = await Session.find({token});
console.log("Found Session", session);
} catch(error) {
next(error)
}
} else {
console.log("in token util, token is not present");
const generatedToken = (Math.random()*1e18).toString(36);
}
}
It gives me this result from output of Found Session
Found Session [ model {
'$__':
InternalCache {
strictMode: true,
selected: {},
shardval: undefined,
saveError: undefined,
validationError: undefined,
adhocPaths: undefined,
removing: undefined,
inserting: undefined,
saving: undefined,
version: undefined,
getters: {},
_id: 5ae31a2062728504f78ee860,
populate: undefined,
populated: undefined,
wasPopulated: false,
scope: undefined,
activePaths:
StateMachine {
paths:
{ token: 'init',
context: 'init',
contextArray: 'init',
_id: 'init',
__v: 'init' },
states:
{ ignore: {},
default: {},
init:
{ _id: true,
context: true,
contextArray: true,
token: true,
__v: true },
modify: {},
require: {} },
stateNames: [ 'require', 'modify', 'init', 'default', 'ignore' ] },
pathsToScopes: {},
session: null,
ownerDocument: undefined,
fullPath: undefined,
emitter:
EventEmitter {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: 0 },
'$options':
{ skipId: true,
isNew: false,
skipDefaults:
{ _id: true,
context: true,
contextArray: true,
token: true,
__v: true } } },
isNew: false,
errors: undefined,
_doc:
{ context: 'client',
contextArray:
[ toBSON: [Function: toBSON],
_atomics: {},
_parent: [Circular],
_cast: [Function: _cast],
_markModified: [Function: _markModified],
_registerAtomic: [Function: _registerAtomic],
'$__getAtomics': [Function: $__getAtomics],
hasAtomics: [Function: hasAtomics],
_mapCast: [Function: _mapCast],
push: [Function: push],
nonAtomicPush: [Function: nonAtomicPush],
'$pop': [Function: $pop],
pop: [Function: pop],
'$shift': [Function: $shift],
shift: [Function: shift],
pull: [Function: pull],
splice: [Function: splice],
unshift: [Function: unshift],
sort: [Function: sort],
addToSet: [Function: addToSet],
set: [Function: set],
toObject: [Function: toObject],
inspect: [Function: inspect],
indexOf: [Function: indexOf],
remove: [Function: pull],
_path: 'contextArray',
isMongooseArray: true,
validators: [],
_schema: SchemaArray {
casterConstructor: { [Function: SchemaString] schemaName: 'String' },
caster:
SchemaString {
enumValues: [],
regExp: null,
path: 'contextArray',
instance: 'String',
validators:
[ { validator: [Function],
message: 'Path `{PATH}` is required.',
type: 'required' } ],
setters: [],
getters: [],
options: { required: true },
_index: null,
isRequired: true,
requiredValidator: [Function],
originalRequiredValue: true },
'$isMongooseArray': true,
path: 'contextArray',
instance: 'Array',
validators: [],
setters: [],
getters: [],
options: { type: [ { type: [Function: String], required: true } ] },
_index: null,
defaultValue: { [Function: defaultFn] '$runBeforeSetters': true } } ],
_id: 5ae31a2062728504f78ee860,
token: '3agcnp5ufl8g',
__v: 0 },
'$init': true } ]

db.collection is not a function? What?

I am learning mongodb and following a tutorial with the below code:
My index.js file:
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://u****:p****#ds131687.mlab.com:31687/learning_mongo';
var findDocuments = function(db, callback) {
var collection = db.collection('tours');
collection.find().toArray(function(err,docs){
if (err) throw err;
console.log(docs);
callback;
})
}
MongoClient.connect(url, function(err, db){
if (err) throw err;
// console.log("it is working");
// db.close();
findDocuments(db, function(){
db.close();
});
})
Unfortunately, I get the following error in terminal:
dosstx:~/workspace $ node index.js
/home/ubuntu/workspace/node_modules/mongodb/lib/mongo_client.js:810
throw err;
^
TypeError: db.collection is not a function
at findDocuments (/home/ubuntu/workspace/index.js:6:25)
at /home/ubuntu/workspace/index.js:20:5
at args.push (/home/ubuntu/workspace/node_modules/mongodb/lib/utils.js:404:72)
at /home/ubuntu/workspace/node_modules/mongodb/lib/mongo_client.js:255:5
at connectCallback (/home/ubuntu/workspace/node_modules/mongodb/lib/mongo_client.js:933:5)
at /home/ubuntu/workspace/node_modules/mongodb/lib/mongo_client.js:807:13
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)
Does anyone have any advice on how to proceed and/or what is causing the error? The tutorial author does not get this error and I can't see what else is different for me (other than possible different versions of MongoDB vs the author's?)
console.log(db) shows:
MongoClient {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
s:
{ url: 'mongodb://****:****#ds131687.mlab.com:31687/learning_mongo',
options:
{ user: *****,
password: ****,
socketOptions: {},
read_preference_tags: null,
readPreference: [Object],
dbName: 'learning_mongo',
servers: [Object],
auth: [Object],
server_options: [Object],
db_options: [Object],
rs_options: [Object],
mongos_options: [Object],
socketTimeoutMS: 360000,
connectTimeoutMS: 30000,
promiseLibrary: [Function: Promise] },
promiseLibrary: [Function: Promise],
dbCache: {},
sessions: [] },
topology:
Server {
domain: null,
_events:
{ serverOpening: [Function],
serverDescriptionChanged: [Function],
serverHeartbeatStarted: [Function],
serverHeartbeatSucceeded: [Function],
serverHeartbeatFailed: [Function],
serverClosed: [Function],
topologyOpening: [Function],
topologyClosed: [Function],
topologyDescriptionChanged: [Function],
joined: [Function],
left: [Function],
ping: [Function],
ha: [Function],
authenticated: [Function],
error: [Function],
timeout: [Function],
close: [Function],
parseError: [Function],
open: [Object],
fullsetup: [Object],
all: [Object],
reconnect: [Function] },
_eventsCount: 22,
_maxListeners: undefined,
clientInfo:
{ driver: [Object],
os: [Object],
platform: 'Node.js v6.11.2, LE' },
s:
{ coreTopology: [Object],
sCapabilities: null,
clonedOptions: [Object],
reconnect: true,
emitError: true,
poolSize: 5,
storeOptions: [Object],
store: [Object],
host: 'ds131687.mlab.com',
port: 31687,
options: [Object],
sessionPool: [Object],
promiseLibrary: [Function: Promise] } } }
The connect function has changed on new version of mongodb. This should work
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://u****:p****#ds131687.mlab.com:31687/learning_mongo';
var findDocuments = function(db, callback) {
var collection = db.collection('tours');
collection.find().toArray(function(err,docs){
if (err) throw err;
console.log(docs);
callback;
})
}
MongoClient.connect(url, function(err, client){
if (err) throw err;
// console.log("it is working");
// db.close();
findDocuments(client.db('learning_mongo'), function(){
db.close();
});
})
More documentation on this http://mongodb.github.io/node-mongodb-native/3.0/api/
I followed this question and was able to solve the error. Basically, I had to add the following modification to my index.js file:
MongoClient.connect('mongodb://localhost', function (err, client) {
if (err) throw err;
var db = client.db('mytestingdb');
db.collection('customers').findOne({}, function (findErr, result) {
if (findErr) throw findErr;
console.log(result.name);
client.close();
});
});
db.collection() is not a function in the latest version of MongoDB. First uninstall the latest version of MongoDB and then install version number 2.2.33 of MongoDB.
npm uninstall mongodb
npm install mongodb#2.2.33
Version MongoDB >= 3 - That database variable is actually the parent object of the object you are trying to access.

Protractor - To log a value from field in Console in protractor

I am trying to enter a value through sendkeys method to an email field and I am trying to print it out in console using getAttribute('value') but it is always printing out the whole methoda available for the element instead of just printing out the value of the email field. Is there any other way I can achieve this ?
var email = element(by.xpath("//input[#name='email']"));
email.sendKeys('vija' + Date.now() + '#test.com');
console.log(email.getAttribute('value'));
and the output is
{ parentElementArrayFinder:
{ getWebElements: [Function],
actionResults_:
{ then: [Function: then],
cancel: [Function: cancel],
isPending: [Function: isPending] },
locator_: { using: 'xpath', value: '//input[#name=\'email\']' },
click: [Function],
sendKeys: [Function],
getTagName: [Function],
getCssValue: [Function],
getAttribute: [Function],
getText: [Function],
getSize: [Function],
getLocation: [Function],
You have to resolve the promise to get the value:
var email = element(by.xpath("//input[#name='email']"));
email.sendKeys('vija' + Date.now() + '#test.com');
email.getAttribute('value').then(function(inputValue) {
console.log(inputValue);
});