NodeJS + mongoose - user dynamic database globally - node.js

I am using NodeJS, ExpressJS, express-session, connect-mongo and mongoose. I want to create a database for every user. On login the database connection should be globally to use.
This is the: loginController
exports.loginPost = (req, res, next) => {
const email = req.body.email;
const pass = req.body.password;
const pin = req.body.pin;
if (email && pass && pin) {
User.findOne({ email })
.then(u => {
bcrypt.compare(pass, u.password, (err, result) => {
if (!err) {
bcrypt.compare(pin, u.pin, (err2, result2) => {
if (!err2) {
let msg = {};
global.userDB = null;
msg.success = [{ text: "You are now logged in..." }];
req.session.loggedIn = true;
req.session.userId = u._id;
req.session.role= u.role;
const Mongoose = require("mongoose").Mongoose;
const inst = new Mongoose();
let db = "user-" + orgid;
global.userDB = inst.connect(
"mongodb://localhost:27017?authSource=dbWithUserCredentials",
{
useNewUrlParser: true,
auth: { authSource: "admin" },
user: "root",
pass: "root",
dbName: db,
autoReconnect: true
}
);
return res.redirect("/");
} else {
console.log(err2);
}
});
} else {
return res.render("login", {
req,
msg: null
});
}
});
})
.catch(err => {
return res.render("login", {
req,
msg: err
});
});
}
};
This is the adressModel:
const aschema = global.userDB.Schema;
var AdressSchema = new aschema({
name: {
type: String
}
});
var Address = global.userDB.model("Adress", AdressSchema);
module.exports = Address;
When I'm running a page where I'm using this model, i see this on the console when I'm using this command: "console.log(global.userDB)";
NativeConnection {
base:
Mongoose {
connections: [ [Circular] ],
models: {},
modelSchemas: {},
options: { pluralization: true },
plugins: [ [Array], [Array], [Array] ] },
collections: {},
models: {},
config: { autoIndex: true },
replica: false,
hosts: null,
host: 'localhost',
port: 27017,
user: 'root',
pass: 'root',
name: 'user-undefined',
options:
{ pass: 'root',
user: 'root',
auth: { authSource: 'admin' },
useNewUrlParser: true,
db: { forceServerObjectId: false, w: 1 },
server: { socketOptions: {}, auto_reconnect: true },
replset: { socketOptions: {} },
mongos: undefined },
otherDbs: [],
states:
[Object: null prototype] {
'0': 'disconnected',
'1': 'connected',
'2': 'connecting',
'3': 'disconnecting',
'4': 'unauthorized',
'99': 'uninitialized',
disconnected: 0,
connected: 1,
connecting: 2,
disconnecting: 3,
unauthorized: 4,
uninitialized: 99 },
_readyState: 2,
_closeCalled: false,
_hasOpened: false,
_listening: false,
db:
Db {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
s:
{ databaseName: 'user-undefined',
dbCache: {},
children: [],
topology: [Server],
options: [Object],
logger: [Logger],
bson: BSON {},
authSource: undefined,
readPreference: undefined,
bufferMaxEntries: -1,
parentDb: null,
pkFactory: undefined,
nativeParser: undefined,
promiseLibrary: [Function: Promise],
noListener: false,
readConcern: undefined },
serverConfig: [Getter],
bufferMaxEntries: [Getter],
databaseName: [Getter] } }
Can someone say, why i get an 'undefined' in the database-name, but when I console.log the 'db'-variable there is the correct user._id.
Thanks!

Related

server doesn't send response for Sequelize many to many relationship query

I am new to sequelize and node js. I have been trying to implement Sequelize Many-to-Many Association using node.js, express with PostgreSQL database following this tutorial. I have implemented a single table and retrieve data correctly without any issue. But in many-to-many relationships, I can only print data to console and in postman and chrome, it keeps loading around a minute and wait without loading data. Here are my code files.
db config file
const dbConfig = require("../config/db.config.js");
const Sequelize = require("sequelize");
const sequelize = new Sequelize(dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {
host: dbConfig.HOST,
dialect: dbConfig.dialect,
operatorsAliases: false,
define: {
timestamps: true,
freezeTableName: true
},
pool: {
max: dbConfig.pool.max,
min: dbConfig.pool.min,
acquire: dbConfig.pool.acquire,
idle: dbConfig.pool.idle
}
});
const db = {};
db.Sequelize = Sequelize;
db.sequelize = sequelize;
db.actor = require("./actor.model.js")(sequelize, Sequelize);
db.film = require("./film.model.js")(sequelize, Sequelize);
db.film_actor = require("./film_actor.model.js")(sequelize, Sequelize);
db.film.belongsToMany(db.actor, {
through: db.film_actor,
as: "actors",
foreignKey: "film_id",
});
db.actor.belongsToMany(db.film, {
through: db.film_actor,
as: "films",
foreignKey: "actor_id",
});
module.exports = db;
filmController file
const db = require("../models");
const Film = db.film;
const Actor = db.actor;
//find all films including actors
exports.findAll = () => {
return Film.findAll({
include: [
{
model: Actor,
as: "actors",
attributes: ["first_name", "last_name"],
through: {
attributes: [],
}
},
],
})
.then((film) => {
console.log(film[5]);
return film;
})
.catch((err) => {
console.log(">> Error while retrieving films: ", err);
});
};
// find film by film id
exports.findById = (req, res) => {
const film_id = req.params.id;
return Film.findByPk(film_id, {
include: [
{
model: Actor,
as: "actors",
attributes: ["first_name", "last_name"],
through: {
attributes: [],
}
},
],
})
.then((films) => {
return films;
})
.catch((err) => {
console.log(">> Error while finding film: ", err);
});
};
film.route file
module.exports = app => {
const film = require("../controllers/film.controller.js");
var router = require("express").Router();
// Retrieve all films
router.get("/films", film.findAll);
// Retrieve a single actor with id
router.get("/films/:id", film.findById);
app.use('/api', router);
};
server.js file
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const filmController = require("./app/controllers/film.controller");
const app = express();
const db = require("./app/models");
db.sequelize.sync();
var corsOptions = {
origin: "http://localhost:8081"
};
app.use(cors(corsOptions));
// parse requests of content-type - application/json
app.use(express.json());
// parse requests of content-type - application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));
// simple route
app.get("/", (req, res) => {
res.json({ message: "Welcome to bezkoder application." });
});
db.sequelize.sync().then(() => {
// run();
});
require("./app/routes/actor.routes")(app);
require("./app/routes/film.routes")(app);
// app.get('/films',filmController.findAll);
// set port, listen for requests
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}.`);
});
As per my understanding, the issue should be about the routing. I created route for many to many associations as the same way I did for singe table(actor) but this problem occurred. I put a console log under findAll() method in filCcontroller and it prints the data in the console along with the query.
This is the output on my console
Executing (default): SELECT "film"."film_id", "film"."title", "film"."description", "film"."release_year", "film"."language_id", "film"."rental_duration", "film"."length", "actors"."actor_id" AS "actors.actor_id", "actors"."first_name" AS "actors.first_name", "actors"."last_name" AS "actors.last_name" FROM "film" AS "film" LEFT OUTER JOIN ( "film_actor" AS "actors->film_actor" INNER JOIN "actor" AS "actors" ON
"actors"."actor_id" = "actors->film_actor"."actor_id") ON "film"."film_id" = "actors->film_actor"."film_id";
film {
dataValues: {
film_id: 166,
title: 'Color Philadelphia',
description: 'A Thoughtful Panorama of a Car And a Crocodile who must Sink a Monkey in The Sahara Desert',
release_year: 2006,
language_id: 1,
rental_duration: 6,
length: 149,
actors: [
[actor], [actor],
[actor], [actor],
[actor], [actor],
[actor]
]
},
_previousDataValues: {
film_id: 166,
title: 'Color Philadelphia',
description: 'A Thoughtful Panorama of a Car And a Crocodile who must Sink a Monkey in The Sahara Desert',
release_year: 2006,
language_id: 1,
rental_duration: 6,
length: 149,
actors: [
[actor], [actor],
[actor], [actor],
[actor], [actor],
[actor]
]
},
_changed: Set {},
_options: {
isNewRecord: false,
_schema: null,
_schemaDelimiter: '',
include: [ [Object] ],
includeNames: [ 'actors' ],
includeMap: { actors: [Object] },
includeValidated: true,
attributes: [
'film_id',
'title',
'description',
'release_year',
'language_id',
'rental_duration',
'length'
],
raw: true
},
isNewRecord: false,
actors: [
actor {
dataValues: [Object],
_previousDataValues: [Object],
_changed: Set {},
_options: [Object],
isNewRecord: false
},
actor {
dataValues: [Object],
_previousDataValues: [Object],
_changed: Set {},
_options: [Object],
isNewRecord: false
},
actor {
dataValues: [Object],
_previousDataValues: [Object],
_changed: Set {},
_options: [Object],
isNewRecord: false
},
actor {
dataValues: [Object],
_previousDataValues: [Object],
_changed: Set {},
_options: [Object],
isNewRecord: false
},
actor {
dataValues: [Object],
_previousDataValues: [Object],
_changed: Set {},
_options: [Object],
isNewRecord: false
},
actor {
dataValues: [Object],
_previousDataValues: [Object],
_changed: Set {},
_options: [Object],
isNewRecord: false
},
actor {
dataValues: [Object],
_previousDataValues: [Object],
_changed: Set {},
_options: [Object],
isNewRecord: false
}
]
}
any help would be greatly appreciated.

.patch() do not saves the parameter to the database in Objection.js with Knex

I am creating Express API and I am using Objection.js as ORM with Knex.js
I have created router for updating user password from the profile with 2 fields (old password and the new password),first it verifies the old password (protection from stealing JWT token). After it returns valid condition then I proceed to hash the new password with bcrypt and update it with .patch() otherwise it will return validation error the old password it is not the correct password. The problem is when I send the same exact request it goes through meaning that .patch not worked and did not save the new password to the database. Can anyone explain some solution to this problem or probably hit me with some documention on how to fix it
The code is bellow:
router.patch('/updatepassword', async (req, res, next) => {
const { id } = req.user;
const {
oldPassword,
newPassword,
} = req.body;
try {
await passwordSchema.validate({
oldPassword,
newPassword,
}, {
abortEarly: false
});
const UserOldPassword = await User.query().select('password').findById(id);
const validOldPassword = await bcrypt.compare(oldPassword, UserOldPassword.password);
if (validOldPassword) {
const hashedPassword = await bcrypt.hash(newPassword, 12);
const defi = User.query().patch({ password: hashedPassword }).where('id', id).returning('*')
.first();
console.log(defi);
res.status(200).json({
message: returnMessage.passwordUpdated
});
} else {
const error = new Error(returnMessage.invalidOldPassword);
res.status(403);
throw error;
}
} catch (error) {
next(error);
}
});
Console log:
QueryBuilder {
_modelClass: [Function: User],
_operations: [
UpdateOperation {
name: 'patch',
opt: [Object],
adderHookName: null,
parentOperation: null,
childOperations: [],
model: [User],
modelOptions: [Object]
},
KnexOperation {
name: 'where',
opt: {},
adderHookName: null,
parentOperation: null,
childOperations: [],
args: [Array]
},
ReturningOperation {
name: 'returning',
opt: {},
adderHookName: null,
parentOperation: null,
childOperations: [],
args: [Array]
},
FirstOperation {
name: 'first',
opt: {},
adderHookName: null,
parentOperation: null,
childOperations: []
}
],
_context: QueryBuilderContext {
userContext: QueryBuilderUserContext { [Symbol()]: [Circular] },
options: InternalOptions {
skipUndefined: false,
keepImplicitJoinProps: false,
isInternalQuery: false,
debug: false
},
knex: null,
aliasMap: null,
tableMap: null,
runBefore: [],
runAfter: [],
onBuild: []
},
_parentQuery: null,
_isPartialQuery: false,
_activeOperations: [],
_resultModelClass: null,
_explicitRejectValue: null,
_explicitResolveValue: null,
_modifiers: {},
_allowedGraphExpression: null,
_findOperationOptions: {},
_relatedQueryFor: null,
_findOperationFactory: [Function: findOperationFactory],
_insertOperationFactory: [Function: insertOperationFactory],
_updateOperationFactory: [Function: updateOperationFactory],
_patchOperationFactory: [Function: patchOperationFactory],
_relateOperationFactory: [Function: relateOperationFactory],
_unrelateOperationFactory: [Function: unrelateOperationFactory],
_deleteOperationFactory: [Function: deleteOperationFactory]
}
PATCH /v1/profile/updatepassword 200 1346.797 ms - 42
Solution: Do not forget to put await on async function.

using #each in handlebars not working

I have a var with products and if I console log it out it shows this.
Query {
_mongooseOptions: {},
mongooseCollection:
NativeCollection {
collection: null,
opts: { bufferCommands: true, capped: false },
name: 'products',
collectionName: 'products',
conn:
NativeConnection {
base: [Object],
collections: [Object],
models: [Object],
config: [Object],
replica: false,
hosts: null,
host: null,
port: null,
user: null,
pass: null,
name: null,
options: null,
otherDbs: [],
_readyState: 0,
_closeCalled: false,
_hasOpened: false,
_listening: false },
queue: [],
buffer: true,
emitter:
EventEmitter {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined } },
model:
{ [Function: model]
hooks: Kareem { _pres: {}, _posts: {} },
base:
Mongoose {
connections: [Object],
plugins: [],
models: [Object],
modelSchemas: [Object],
options: [Object] },
modelName: 'Product',
model: [Function: model],
db:
NativeConnection {
base: [Object],
collections: [Object],
models: [Object],
config: [Object],
replica: false,
hosts: null,
host: null,
port: null,
user: null,
pass: null,
name: null,
options: null,
otherDbs: [],
_readyState: 0,
_closeCalled: false,
_hasOpened: false,
_listening: false },
discriminators: undefined,
schema:
Schema {
obj: [Object],
paths: [Object],
subpaths: {},
virtuals: [Object],
singleNestedPaths: {},
nested: {},
inherits: {},
callQueue: [Object],
_indexes: [],
methods: {},
statics: {},
tree: [Object],
_requiredpaths: undefined,
discriminatorMapping: undefined,
_indexedpaths: undefined,
query: {},
childSchemas: [],
s: [Object],
options: [Object],
'$globalPluginsApplied': true },
collection:
NativeCollection {
collection: null,
opts: [Object],
name: 'products',
collectionName: 'products',
conn: [Object],
queue: [],
buffer: true,
emitter: [Object] },
Query: { [Function] base: [Object] },
'$__insertMany': [Function],
insertMany: [Function] },
schema:
Schema {
obj:
{ imagePath: [Object],
title: [Object],
description: [Object],
price: [Object] },
paths:
{ imagePath: [Object],
title: [Object],
description: [Object],
price: [Object],
_id: [Object],
__v: [Object] },
subpaths: {},
virtuals: { id: [Object] },
singleNestedPaths: {},
nested: {},
inherits: {},
callQueue: [ [Object], [Object], [Object], [Object] ],
_indexes: [],
methods: {},
statics: {},
tree:
{ imagePath: [Object],
title: [Object],
description: [Object],
price: [Object],
_id: [Object],
id: [Object],
__v: [Function: Number] },
_requiredpaths: undefined,
discriminatorMapping: undefined,
_indexedpaths: undefined,
query: {},
childSchemas: [],
s: { hooks: [Object], kareemHooks: [Object] },
options:
{ retainKeyOrder: false,
typeKey: 'type',
id: true,
noVirtualId: false,
_id: true,
noId: false,
validateBeforeSave: true,
read: null,
shardKey: null,
autoIndex: null,
minimize: true,
discriminatorKey: '__t',
versionKey: '__v',
capped: false,
bufferCommands: true,
strict: true,
pluralization: true },
'$globalPluginsApplied': true },
op: 'find',
options: { retainKeyOrder: false },
_conditions: {},
_fields: undefined,
_update: undefined,
_path: undefined,
_distinct: undefined,
_collection:
NodeCollection {
collection:
NativeCollection {
collection: null,
opts: [Object],
name: 'products',
collectionName: 'products',
conn: [Object],
queue: [],
buffer: true,
emitter: [Object] },
collectionName: 'products' },
_traceFunction: undefined,
_castError: null,
_count: [Function],
_execUpdate: [Function],
_find: [Function],
_findOne: [Function],
_findOneAndRemove: [Function],
_findOneAndUpdate: [Function] }
I am trying to use #each to get the products and show lets say the title first.
Here is my method in index js using node
var express = require('express');
var router = express.Router();
var Product = require('../models/product');
/* GET home page. */
router.get('/', function(req, res, next) {
Product.find({}, function (err, products) {
// check for and handle query errors
if (err) {
console.error('Product.find() error', err);
return next(err);
}
// continue to render the view with `products` available
console.log(products);
res.render('shop/index', { title: 'Shopping Cart', products: products });
});
});
module.exports = router;
And here is the foreach sentence at index.hbs
{{#each products}}
<p>{{products.price}}</p>
{{/each}}
I tried different ways like #each this and then getting it but non seem working.
Just incase if needed when I search in the db
> db.products.find()
{ "_id" : ObjectId("5855c55482d8722419e21a7d"), "imagePath" : "https://upload.wikimedia.org/wikipedia/en/thumb/5/5e/Gothiccover.png/250px-Gothiccover.png", "title" : "weeee", "description" : " AWeeesomeee", "price" : "15", "__v" : 0 }
{ "_id" : ObjectId("5855c55482d8722419e21a7e"), "imagePath" : "https://upload.wikimedia.org/wikipedia/en/thumb/5/5e/Gothiccover.png/250px-Gothiccover.png", "title" : "Gowwww", "description" : " this is great", "price" : "15", "__v" : 0 }
{ "_id" : ObjectId("5855c55482d8722419e21a7f"), "imagePath" : "https://upload.wikimedia.org/wikipedia/en/thumb/5/5e/Gothiccover.png/250px-Gothiccover.png", "title" : "killaa crw", "description" : " i love it", "price" : "15", "__v" : 0 }
{ "_id" : ObjectId("5855c55482d8722419e21a80"), "imagePath" : "https://upload.wikimedia.org/wikipedia/en/thumb/5/5e/Gothiccover.png/250px-Gothiccover.png", "title" : "joker", "description" : " kill em", "price" : "15", "__v" : 0 }
{ "_id" : ObjectId("5855c55482d8722419e21a81"), "imagePath" : "https://upload.wikimedia.org/wikipedia/en/thumb/5/5e/Gothiccover.png/250px-Gothiccover.png", "title" : "harley", "description" : " naughtttyyy", "price" : "15", "__v" : 0 }
{ "_id" : ObjectId("5855c55482d8722419e21a82"), "imagePath" : "https://upload.wikimedia.org/wikipedia/en/thumb/5/5e/Gothiccover.png/250px-Gothiccover.png", "title" : "suicide", "description" : " squad", "price" : "15", "__v" : 0 }
> db.products.count()
6
App.js file
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var expressHbs = require('express-handlebars');
var mongoose = require('mongoose');
var routes = require('./routes/index');
var app = express();
app.connect('localhost:27017/shopping');
// view engine setup
app.engine('.hbs', expressHbs({defaultLayout : 'layout', extname: '.hbs' }));
app.set('view engine', '.hbs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
Mongoose' model.find() doesn't return the results directly as Mongo's command-line does.
var products = Product.find();
It expects a callback function to be provided either to it directly, following the conditions, or provided to a method of the Query object it returns:
function proceedWithProducts(err, products) {
if (err) {
// handler query error
} else {
// use products
}
}
// a couple options...
Product.find({}, proceedWithProducts);
Product.find().exec(proceedWithProducts);
Within the route:
/* GET home page. */
router.get('/', function(req, res, next) {
Product.find({}, function (err, products) {
// check for and handle query errors
if (err) {
console.error('Product.find() error', err);
return next(err);
}
// continue to render the view with `products` available
console.log(products);
res.render('shop/index', { title: 'Shopping Cart', products: products });
});
});

Deploying Node-expressjs app in lambda - [Error: socket hang up] code: ECONNRESET

I am trying to deploy my Expressjs application into lambda, but i am getting below error. Please try to me to resolve this error.
lambda response:
{
"statusCode": 502,
"body": "",
"headers": {}
}
lambda log (it contains console of mongo connection and error)
NativeConnection {
base:
Mongoose {
connections: [ [Circular] ],
plugins: [],
models: { Student: [Object] },
modelSchemas: { Student: [Object] },
options: { pluralization: true } },
collections:
{ student:
NativeCollection {
collection: [Object],
opts: [Object],
name: 'student',
collectionName: 'student',
conn: [Circular],
queue: [],
buffer: false,
emitter: [Object] } },
models:
{ Student:
{ [Function: model]
hooks: [Object],
base: [Object],
modelName: 'Student',
model: [Function: model],
db: [Circular],
discriminators: undefined,
schema: [Object],
collection: [Object],
Query: [Object],
'$__insertMany': [Function],
insertMany: [Function] } },
config: { autoIndex: true },
replica: false,
hosts: null,
host: '1.0.0.0.0',
port: 3000,
user: undefined,
pass: undefined,
name: 'sudentdb',
options:
{ mongos: {},
db: { safe: true, forceServerObjectId: false },
auth: {},
server: { socketOptions: {}, auto_reconnect: true },
replset: { socketOptions: {} } },
otherDbs: [],
_readyState: 1,
_closeCalled: false,
_hasOpened: true,
_listening: false,
db:
EventEmitter {
domain: null,
_events:
{ close: [Function],
error: [Function],
reconnect: [Function],
timeout: [Function],
open: [Function],
parseError: [Function] },
_eventsCount: 6,
_maxListeners: undefined,
s:
{ databaseName: 'studentdb',
dbCache: {},
children: [],
topology: [Object],
options: [Object],
logger: [Object],
bson: {},
authSource: undefined,
readPreference: undefined,
bufferMaxEntries: -1,
parentDb: null,
pkFactory: undefined,
nativeParser: undefined,
promiseLibrary: [Function: Promise],
noListener: false,
readConcern: undefined },
serverConfig: [Getter],
bufferMaxEntries: [Getter],
databaseName: [Getter],
_listening: true },
_events:
{ connected: [Function],
error: [Function],
disconnected: [Function] },
_eventsCount: 3 }
{ [Error: socket hang up] code: 'ECONNRESET' }
student.model.js
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var studentSchema = new Schema({
name: String,
rollnumber: Number,
},{collection:"student"});
module.exports = mongoose.model('Student', studentSchema);
api/student(REST API - GET method)
exports.index = function(req, res) {
console.log(mongoose.connection)
Student.findOne({},function(err,doc){
if(err){
return res.json("error found");
}else{
return res.json(doc);
}
});
};
lambda.js
'use strict'
const awsServerlessExpress = require('aws-serverless-express');
const app = require('./bin/www');
const server = awsServerlessExpress.createServer(app);
exports.handler = (event,context)=>{
console.log("EVENT: " + JSON.stringify(event));
awsServerlessExpress.proxy(server,event,context);
}

Rethinkdb query always returns null Eventhough data is existed?

I am new to rethinkDB,I am trying to find data by username using filter function.
But rethinkDB returns null eventhough data existed.
//Define Your Api//Define Your Api
import express from 'express';
import r from 'rethinkdb';
const router = express.Router();
router.post('/users',(req,res)=>{
let username = req.body.data.username;
let password = req.body.data.password;
console.log(username,password);
r.connect({db:"image"}).then((conn) => {
r.table("users").filter({username:"arfo"}).run(conn,function (err, data) {
console.log(data) //null
})
})
});
export default router
Updated
it returns me a bunch of data like this do i have to manipulate this data
Cursor {
_type: 3,
_eachCb: [Function],
_conn:
TcpConnection {
host: 'localhost',
port: 28015,
db: 'image',
authKey: '',
timeout: 20,
ssl: false,
outstandingCallbacks: {},
nextToken: 2,
open: true,
closing: false,
buffer: <Buffer >,
_events: {},
_eventsCount: NaN,
_closePromise: null,
rawSocket:
Socket {
connecting: false,
_hadError: false,
_handle: [Object],
_parent: null,
_host: 'localhost',
_readableState: [Object],
readable: true,
domain: null,
_events: [Object],
_eventsCount: 7,
_maxListeners: undefined,
_writableState: [Object],
writable: true,
allowHalfOpen: false,
destroyed: false,
_bytesDispatched: 325,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: null,
_server: null,
user: 'admin',
password: '',
read: [Function],
_consuming: true } },
_token: 1,
_opts: {},
_root: { [Function] args: [ [Object], [Object] ], optargs: {} },
_responses: [ { t: 2, r: [Object], n: [] } ],
_responseIndex: 0,
_outstandingRequests: 0,
_iterations: 0,
_endFlag: true,
_contFlag: false,
_closeAsap: false,
_cont: null,
_cbQueue: [],
_closeCb: null,
_closeCbPromise: null,
next: [Function] }
From the RethinkDB docs, it looks like run returns (err, data). For example (from the docs):
r.table('marvel').run(conn, function(err, cursor) {
cursor.each(console.log);
})
So if you update your code to:
r.table("users").filter({username:"arfo"}).run(conn,function (err, data) {
console.log(data)
})
Then it should remove the null log that you were seeing.
I'm no RethinkDB expert, but from the docs it looks like if you want to get the data from the response then you can call toArray on the cursor:
r.table("test").run( conn, function(error, cursor) {
cursor.toArray( function(error, results) {
console.log(results) // results is an array of documents
})
})

Resources