Returning back an array of collections in mongoose - node.js

I am new to mongoose and I tried to search a lot in order to convert a mongoose collection into an array but it returns an error that toArray() is not a method.So here is the alternative way I am trying to convert into an array.I am using passport js method for authentication and for that i require all the user information as an array.I am tryin to implement the example given in
https://github.com/jaredhanson/passport-local/blob/master/examples/express3/app.js
to mongoose driven data.
Heres the snippet I am trying to use for converting a mongoose collection into an Array.
ContactProvider.prototype.findByusername=function(callback){
var users=Post.find({});
var user=toObject((JSON.parse(users))) ;
callback(null,user);
};
I got the following error
undefined:1
[object Object]
^
SyntaxError: Unexpected token o
at Object.parse (native)
at ContactProvider.findByusername (/home/r121/Desktop/nilesh/cmarin-MongoDB-Node-Express-Blog-4a5e5e9/postprovider.js:60:26)
at Object.<anonymous> (/home/r121/Desktop/nilesh/cmarin-MongoDB-Node-Express-Blog-4a5e5e9/app.js:138:37)
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)
How should I return an array of those collections backs.Can anyone please guide me with the syntax?

A simple solution would be to utilize the callback of the .find() method, then calling the toObject() on the returned results. Example
Post.find({}).exec(function(err, o) {
callback(err, o)
});
Edit: Removed redundant toObject() call for reasons mentioned in comments by JohnnyHK

Related

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

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.

How do I make generator functions work with Hapi JS

I installed various node.js versions with nvm and tried -harmony flag to make generator functions work with yield keyword but I'm getting all kinds of errors when the server starts. One of them is below:
/home/ubuntu/workspace/node_modules/hapi/node_modules/joi/lib/object.js:310
throw castErr;
^
TypeError: Cannot read property '_items' of undefined
at /home/ubuntu/workspace/node_modules/hapi/node_modules/topo/lib/index.js:39:22
at Array.forEach (native)
at internals.Topo.add (/home/ubuntu/workspace/node_modules/hapi/node_modules/topo/lib/index.js:36:24)
at internals.Object.keys (/home/ubuntu/workspace/node_modules/hapi/node_modules/joi/lib/object.js:301:18)
at internals.root.root.object (/home/ubuntu/workspace/node_modules/hapi/node_modules/joi/lib/index.js:71:72)
at Object.<anonymous> (/home/ubuntu/workspace/node_modules/hapi/node_modules/catbox/lib/policy.js:255:24)
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)
Is there something special I need to do to use the yield keyword?
UPDATE: I updated nodejs to 5.4.1 and the errors are gone. But I can't use the yield function.
Here's a code:
var nodes = yield Db.node.find({ type: 'root' });
return reply.success(nodes);
And here's the error I get:
var nodes = yield Db.node.find({ type: 'root' });
^^
SyntaxError: Unexpected identifier
You'll need a plugin for hapi that allows you to run a generator as handler. Something like https://github.com/ide/hapi-async-handler

How to use System.import() correctly?

I use the jspm in my project.
But I need the server side nodejs file to execute some instruction.
For example, I need to use the lodash and found the guide in the https://github.com/systemjs/systemjs
var System = require('jspm').Loader();
System.import('lodash').then(function (_) { console.log(_); });
However, I want to use the lodash globally.
Just like
var _ = System.import('lodash');
var myArr = _.map([1, 2, 3], function(n) { return n * 3; });
It will show
TypeError: _.map is not a function
at Object. (/Users/joyfeel/javascript/jspm-test/index.js:49:16)
at Module._compile (module.js:435:26)
at normalLoader (/usr/local/lib/node_modules/babel/node_modules/babel-core/lib/api/register/node.js:199:5)
at Object.require.extensions.(anonymous function) [as .js] (/usr/local/lib/node_modules/babel/node_modules/babel-core/lib/api/register/node.js:216:7)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:311:12)
at Function.Module.runMain (module.js:467:10)
at Object. (/usr/local/lib/node_modules/babel/lib/_babel-node.js:144:25)
at Module._compile (module.js:435:26)
at Object.Module._extensions..js (module.js:442:10)
Why does the lodash only be used in .then scope?
Could anyone tell me how to figure it out? Suppose we want to System.import other modules and use it?
_ can only be accessed in the scope of then because System.import always returns a Promise.
Therefore you have to wait for the Promise to be resolved before you can access its result.
Anyway i would not recommend you to use lodash globally.
But when you really want to use _ globally you can do something like:
System.import('lodash').then(function(_) {
GLOBAL._ = _;
});
Still you have to make sure that all code that uses GLOBAL._ waits till the Promise from the lodash import is resolved.
But again: i would discourage you doing it that way but recommend that you import lodash in every module that needs it.

Mongoose Model alias error

I have a funny issue with Mongoose, one of MongoDB's ODMs.
I wanted to alias the mongoose.model method into simply Model. I even checked the alias :
exports = Model = mongoose.model;
console.log(Model === mongoose.model); // returns true
I already did this for mongoose.Schema and it worked seamlessly.
Now when I register a schema using the aliased Model variable :
Model('User', UserSchema);
I get the following error :
/node_modules/mongoose/lib/index.js:257
if (!this.modelSchemas[name]) {
^
TypeError: Cannot read property 'User' of undefined
at Mongoose.model (/node_modules/mongoose/lib/index.js:257:25)
at Object.<anonymous> (/app/models/user.js:20:1)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at controllers_path (/app.js:23:2)
at Array.forEach (native)
But if I use the normal form, I get absolutely no errors :
mongoose.model('User', UserSchema);
Is this a bug in the Mongoose.js ODM or am I missing something ?
When you call mongoose.model(...), the mongoose object is getting passed into the model function as this. When you call the function through your alias, this will be set to global instead of mongoose.
If you really wanted to do this you'd have to do something like:
var Model = mongoose.model.bind(mongoose);
That way, mongoose gets passed into the function no matter how you call Model.
Just to elaborate on #JohnnyHK answer:
var a = {
b:function(){
console.log(this.name)
},
name:"its a"
}
a.b() //logs "its a"
var c = a.b;
c(); //logs undefined
While calling c the invoking context is window or the global object.

Node.js with ExpressJS error: Cannot read property 'prototype' of undefined

Running node.js v0.10.2 and express v3.1.1 (latest at this time) and getting this error:
/root/dmr-addresses/node_modules/jquery/lib/node-jquery.js:10
window.XMLHttpRequest.prototype.withCredentials = false;
^
TypeError: Cannot read property 'prototype' of undefined
at create (/root/dmr-addresses/node_modules/jquery/lib/node-jquery.js:10:26)
at /root/dmr-addresses/node_modules/jquery/lib/node-jquery.js:9503:18
at Object.<anonymous> (/root/dmr-addresses/node_modules/jquery/lib/node-jquery.js:9505:2)
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.require (module.js:362:17)
at require (module.js:378:17)
at Object.<anonymous> (/root/dmr-addresses/address/log.js:1:71)
line 1 of log.js is:
var $ = require('jquery');
I've tried running npm install jquery but it has not fixed the problem.
Check this:
Same error here...
I don't know what I'm doing, but I changed the node-jquery.js fourth-fifth row's and it's start working :)
old:
if(window == null ) {
window = require('jsdom').jsdom().createWindow();
new:
if(!window || !window.document) {
window = require('jsdom').createWindow();
window.document = require('jsdom').jsdom();
You don't actually have a prototype object in Node server code, it's all stored in the much nicer __proto__ object and you should be using Object.create/defineProperty.
What exactly are you trying to do? Run an ajax query with Node? If so, you should be using Nodes http.request
An example could be:
require('request').post({
"uri" : "http://example.com/",
"headers" : {
'content-type': 'application/json'
},
"body" : "hello=world"
},
function(e,r,b){
// e = errors, r = response and b = returned body
console.log(b,r.statusCode));
});
Looks like this is an issue with the jsdom module that node-jquery depends on. It appears that this is a known issue, and that it has been fixed, but not published to npm yet.
Check it out: https://github.com/coolaj86/node-jquery/issues/52

Resources