Getting error while trying to save file in grid-fs using mongoose and nodejs - node.js

Trying to get GridFSBucket working for mongoose but no luck even after spending 2 days on it. I was getting a warning related to GridStore so thought of using GridFSBucket as we are using mongoose so referred the link but the same code is not working for me.
Following is the code I tried -
var express = require('express');
var gridfsService = express.Router();
var mongoose = require('mongoose');
const conn = mongoose.createConnection('mongodb://user:password#127.0.0.1:27017/dbname');
const gridFsBucket = new mongoose.mongo.GridFSBucket(conn.db);
The error I am getting is -
_chunksCollection: db.collection(options.bucketName + '.chunks'),
^
TypeError: Cannot read property 'collection' of undefined
at new GridFSBucket (d:\Projects\myapp\node_modules\mongoose\node_modules\mongodb\lib\gridfs-stream\index.js:50:27)
at Object.<anonymous> (d:\Projects\myapp\services\myapp.service.js:6:22)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Module.require (module.js:596:17)
at require (internal/module.js:11:18)
at Object.<anonymous>
I am using following versions - Nodejs-8.11.2 Mongoose- 5.0.0 mongodb - 4.0.4

Had to downgrade mongoose version from latest seeing to suggestions. It worked on mongoose version 4.13.17 (legacy). Any other solution/suggestion is most welcome.

Related

firebase-fuctions ,TypeError: Cannot read property 'onRequest' of undefined

updated firebase via npm i -g firebase-tools ,
used my firebase id ,
while deploying my function at firebase ( with firebase deploy ) this error results out
Error: Error occurred while parsing your function triggers.
TypeError: Cannot read property 'onRequest' of undefined
at Object.<anonymous> (C:\Users\umer\Desktop\learning chatbots\usingFulfilmentAsWebhook\functions\index.js:9:34)
at Module._compile (internal/modules/cjs/loader.js:701:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
at Module.load (internal/modules/cjs/loader.js:600:32)
at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
at Function.Module._load (internal/modules/cjs/loader.js:531:3)
at Module.require (internal/modules/cjs/loader.js:637:17)
at require (internal/modules/cjs/helpers.js:22:18)
at C:\Users\umer\AppData\Roaming\npm\node_modules\firebase-tools\lib\triggerParser.js:15:15
at Object.<anonymous> (C:\Users\umer\AppData\Roaming\npm\node_modules\firebase-tools\lib\triggerParser.js:53:3)
here is the code
const functions = require('firebase-functions');
exports.webhook = functions.http.onRequest((request,response)=>{
console.log("request.body.result.parameters", request.body.result.parameters);
let params = request.body.result.parameters;
response.send({
speech: `${params.name} your hotel booking request for ${params.roomType} room is forwarded for ${params.persons} persons. We will contact you on ${params.email} soon`
});
});
try after putting "s" in http in below line
exports.webhook = functions.https.onRequest((request,response)=>{
...
}
Add this in your first line
const functions = require('firebase-functions');
Besides, make sure you have necessary packages installed.

nodemon - app crashed - waiting for file changes before starting

I just started learning Node.js. The idea of this small application is to use express and mongosse to store some users in a based cloud database (mongoDB via mlab).
I have two seperate files :
User.js (models/User.js)
var mongoose = require('mongoose');
module.exports = mongoose.model('User', {
email : string ,
pwd : string
});
server.js (dossier root)
var express = require('express')
var cors = require('cors')
var bparser = require('body-parser')
var mongoose = require('mongoose')
var User = require('./models/User.js')
var app = express()
app.use(cors())
app.use(bparser.json())
app.post('/register', (req,res) => {
userData = req.body;
var user = new User(userData);
user.save((err, result) => {
if(err) console.log('IL YA UNE ERREUR')
result.sendStatus(200);
})
})
mongoose.connect('mongodb://user:pwd#ds261755.mlab.com:61755/myapp', { useMongoClient: true } , (erreur) => {
if(!erreur)
console.log('Connexion etablie');
})
app.listen(3000)
When I execute : nodemon server.js, I get the error below:
D:\Bureau\MEAN\appBackend\models\User.js:5
email : string ,
^
ReferenceError: string is not defined
at Object.<anonymous> (D:\Bureau\MEAN\appBackend\models\User.js:5:12)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (D:\Bureau\MEAN\appBackend\server.js:6:12)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:389:7)
[nodemon] app crashed - waiting for file changes before starting...
Do you have any idea about this error?
Mongoose expects you to specify types using the built-in constructor functions, which are named with capital letters, e.g. String, Number, Boolean, etc.
var mongoose = require('mongoose');
module.exports = mongoose.model('User', {
email : String ,
pwd : String
});
define
module.exports = mongoose.model('User', new mongoose.Schema({
email : 'string' ,
pwd : 'string'
})
});
There is no string variable in the code .
this message will be appeared always when there's any small mistake.
I also faced this when module.exports type as module.export,just missed 's' only.
I come across with such error and on my case it was syntax error in the node js file.check your code for error as nodemon listen to change and run if no error there.
This was the error that make app-crashed ....
console.log("this is author",cope["author"];
SyntaxError: missing ) after argument list
at new Script (vm.js:79:7)
at createScript (vm.js:251:10)
at Object.runInThisContext (vm.js:303:10)
at Module._compile (internal/modules/cjs/loader.js:657:28)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
at Function.Module._load (internal/modules/cjs/loader.js:530:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)
at startup (internal/bootstrap/node.js:283:19) After i correct the error [nodemon] restarting due to changes... [nodemon]
starting node server.js
That is it. Check for error in your code the nodemon automatically start the server.That is why nodemon is best rather than using node filename.js cz every time you have to start whenever you change the code.
The common reason is that you're trying to access the database from an IP that isn't whitelisted.
For my case, I was working on the same project on another PC. So, i had to whitelist the PC IP.
To do this, login to your cloud base mongodb, navigate to that your particular db project, and click on network access, add IP address and click on current ip address.
Also, make sure on your terminal, you run mongod to start your mongodb.
That solve for me
[nodemon] app crashed - waiting for file changes before starting...
You can fix this error with adding "start": "nodemon server.js" entry to your package.json file.
Test with this command:
npm install --save express-load
Many times we closed the PC and left the project running, when we used it again and ran the project again, that error appeared. I always solved it, restarting the pc. Everything worked perfectly.

Why does Handlebars.template(templateSpec) not work as (I) expected?

I'm trying to precompile a handlebar template in a node app. Later, I would like to store/retrieve the precompiled template to/from a database and use it.
var handlebars = require('handlebars');
var templateSpec = handlebars.precompile('{{foo}}');
var template = handlebars.template(templateSpec);
I base this code on the Handlebars reference.
The code above throws errors:
/home/ubuntu/workspace/handlebars/node_modules/handlebars/dist/cjs/handlebars/runtime.js:50
throw new _exception2['default']('Unknown template object: ' + typeof templateSpec);
^
Error: Unknown template object: string
at Object.template (/home/ubuntu/workspace/handlebars/node_modules/handlebars/dist/cjs/handlebars/runtime.js:50:11)
at HandlebarsEnvironment.hb.template (/home/ubuntu/workspace/handlebars/node_modules/handlebars/dist/cjs/handlebars.runtime.js:51:20)
at Object.<anonymous> (/home/ubuntu/workspace/handlebars/test.js:5:27)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Function.Module.runMain (module.js:441:10)
at startup (node.js:139:18)
at node.js:990:3
Not sure what I'm doing wrong.

Koa-pg Can't find module pg

Hey so I'm trying to get Nodejs Koa to talk to postgres using the Koa-pg module, but I keep getting a 'Can't find module pg' error.
I've tried to follow the koa-pg examples, but have come up short...so any advice would on how to progress would be appreciated.
If created my app.js file as follows:
var koa = require('koa');
var route = require('koa-route');
var koaPg = require('koa-pg');
var roads = require('./controllers/roads');
var app = module.exports = koa();
app.use(route.get('/roads/bbox/', roads.bbox));
app.listen(3000);
console.log('listening on port 3000');
And then created my controller file as follows:
var credentials = require('../credentials.js');
var environment = credentials.dev;
app.use(koaPg('postgres://' + environment.user + '#' + environment.host + ':' + environment.port + '/' + environment.database))
module.exports.bbox = function * bbox(next) {
var result = yield this.koaPg.db.client.queryPromise('SELECT now()')
console.log('result: ', result)
this.body = result.rows[0].now.toISOString()
};
But I'm getting the following error:
module.js:338
throw err;
^
Error: Cannot find module 'pg'
at Function.Module._resolveFilename (module.js:336:15)
at Function.Module._load (module.js:278:25)
at Module.require (module.js:365:17)
at require (module.js:384:17)
at Object.<anonymous> (c:\Users\User\Documents\restful_koa\node_modul
es\koa-pg\index.js:12:27)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Module.require (module.js:365:17)
This is only a personal project but I'd love to understand where i'm going wrong.
Cheers
As mentioned in the comments:
You need to install the pg module via npm install pg or npm install pg --save if you want to save it to package.json.
The reason you need to do this is koa-pg has co-pg as a dependency so when you install the former the latter is also installed. But pg is not a dependency of co-pg and that is why you have to install it separately.

Function and module.exports error issue NODE.js

:)
I have a somewhat easy answer for you guys to answer as you always do.
Im new at functions and whatnot, iv watched some tutorials about exporting your functions to another node.js application,
Im attempting to generate some random numbers for a external module.
this is what i have setup.
(index.js file)
function randNumb(topnumber) {
var randnumber=Math.floor(Math.random()*topnumber)
}
module.exports.randNumb();
(run.js)
var index = require("./run.js");
console.log(randnumber);
Well My Issue is when i run the index.js file, i get this error from the console.
TypeError: Object #<Object> has no method 'randNumb'
at Object.<anonymous> (C:\Users\Christopher Allen\Desktop\Node Dev Essential
s - Random Number\index.js:8:16)
at Module._compile (module.js:449:26)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.runMain (module.js:492:10)
at process.startup.processNextTick.process._tickCallback (node.js:244:9)
I ran the run.js in the beginning, this is what i got.
ReferenceError: randNumb is not defined
at Object.<anonymous> (C:\Users\Christopher Allen\Desktop\Node Dev Essential
s - Random Number\run.js:3:1)
at Module._compile (module.js:449:26)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.runMain (module.js:492:10)
at process.startup.processNextTick.process._tickCallback (node.js:244:9)
In the randNum function, don't forget to:
return randnumber;
Also in index.js, export the function like so:
exports.randNumb = randNumb;
Invoke it like this in run.js:
console.log(randNumber(10));
You didn't export the var at all.
Your index.js should be :
function randNumb(topnumber) {
return Math.floor(Math.random()*topnumber)
}
module.exports.randnumber = randNumb(10); //replace 10 with any other number...
run.js should be :
var index = require("./run.js");
console.log(index.randnumber);

Resources