Mongorito: save(...).then is not a function - node.js

I tried something similar to the example given on the readme.md file:
var Mongorito = require('mongorito');
var Model = Mongorito.Model;
Mongorito.connect('mongodb://localhost:27017/cr-test');
class User extends Model {
collection() {
return 'users';
}
}
var user1 = new User({
name: "James Gosling",
email: "user1#gmail.com",
password: "changeme"
});
user1.save().then(() => {
console.log('User Created');
});
when I run node --harmony server.js I get this error:
user1.save().then(() => {
^
TypeError: user1.save(...).then is not a function
at Object.<anonymous> (...\app\server.js:24:14)
at Module._compile (module.js:398:26)
at Object.Module._extensions..js (module.js:405:10)
at Module.load (module.js:344:32)
at Function.Module._load (module.js:301:12)
at Function.Module.runMain (module.js:430:10)
at startup (node.js:141:18)
at node.js:980:3
Could someone explain me how could I fix that?

The readme on GitHub is outdated, the project's website now states:
MongoDB ODM for Node.js based on ES6 generators.
No callbacks or promises.
It uses generators, which can find an example of on the getting started page:
'use strict';
function* saveUser () {
var user1 = new User({
name: "James Gosling",
email: "user1#gmail.com",
password: "changeme"
});
yield user1.save();
}
In order for generators to work, you must use 'use strict;' and the function* syntax. This GitHub project has additional examples.
Also, starting with Node v4, you no longer need the --harmony (now a synonym of --es_staging) flag for generators.

or you can do like this also ... but here you can execute just a single statement
user1.save().then(savedUser => console.log(`saved user: ${savedUser}`));

Related

Unexpected token ')' Nodejs with Couchdb

I am using nodejs 14 and couchdb database 3.1.1
I am trying to connect and display list of couchdb databases using nodejs but following error occur
const NodeCouchDb = require('node-couchdb');`
const couch = new NodeCouchDb();
// node-couchdb instance with Memcached
const MemcacheNode = require('node-couchdb-plugin-memcached');
const couchWithMemcache = new NodeCouchDb({
cache: new MemcacheNode
});
// node-couchdb instance talking to external service
const couchExternal = new NodeCouchDb({
host: 'couchdb.external.service',
protocol: 'https',
port: 5984
});
// not admin party
const couchAuth = new NodeCouchDb({
auth: {
user: 'admin',
pass: 'godhelp'
}
});
couch.listDatabases()
.then(
dbs => dbs.map(...),
err => {
// request error occured
});
ERROR After Compiled :
dbs => dbs.map(...),
^
SyntaxError: Unexpected token ')'
at wrapSafe (internal/modules/cjs/loader.js:988:16)
at Module._compile (internal/modules/cjs/loader.js:1036:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10)
at Module.load (internal/modules/cjs/loader.js:937:32)
at Function.Module._load (internal/modules/cjs/loader.js:778:12)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12)
at internal/main/run_main_module.js:17:47
I think there is a syntax error in your code, but more fundamentally node-couchdb seems to be an inactive library that has not been updated in more than four years. I would recommend using nano, which is the official Apache CouchDB NodeJS library.
Here's a simple NodeJS script (index.js) using nano to list your databases.
const nano = require('nano')(process.env.COUCH_URL)
const main = async function() {
const response = await nano.db.list()
console.log(response)
}
main ()
You will need to create an environment variable called COUCH_URL:
export COUCH_URL="http://user:password#localhost:5984"
and then run the script:
node index.js
#[ 'deeds' ]

How can I store my salt as a string, while still using it as a buffer later?

I'm trying to salt a password, however I get the following error message:
(node:958) MaxListenersExceededWarning: Possible EventEmitter memory
leak detected. 11 exit listeners added. Use emitter.setMaxListeners()
to increase limit
TypeError: Salt must be a buffer
at pbkdf2 (crypto.js:644:20)
at Object.exports.pbkdf2 (crypto.js:624:10)
at model.exports.UserCredentialsSchema.methods.setPassword (/Users/friso/Documents/projects/MEANpress/server/src/schemas/user-credentials.schema.ts:35:5)
at App.setupMongoose (/Users/friso/Documents/projects/MEANpress/server/src/App.ts:42:15)
at new App (/Users/friso/Documents/projects/MEANpress/server/src/App.ts:14:14)
at Object.<anonymous> (/Users/friso/Documents/projects/MEANpress/server/src/server.ts:5:13)
at Module._compile (module.js:635:30)
at Module.m._compile (/Users/friso/Documents/projects/MEANpress/server/node_modules/ts-node/src/index.ts:439:23)
at Module._extensions..js (module.js:646:10)
at Object.require.extensions.(anonymous function) [as .ts] (/Users/friso/Documents/projects/MEANpress/server/node_modules/ts-node/src/index.ts:442:12)
at Module.load (module.js:554:32)
at tryModuleLoad (module.js:497:12)
at Function.Module._load (module.js:489:3)
at Function.Module.runMain (module.js:676:10)
at Object.<anonymous> (/Users/friso/Documents/projects/MEANpress/server/node_modules/ts-node/src/bin.ts:157:12)
at Module._compile (module.js:635:30)
I'm trying to do it for this schema and method:
export var UserCredentialsSchema: Schema = new Schema({
username: {
type: String,
lowercase: true,
unique: true
},
password: String,
salt: String
});
UserCredentialsSchema.methods.setPassword = function (password: string): void {
randomBytes(saltLength, (err, buf) => {
console.error(err);
this.salt = buf.toString();
});
pbkdf2(password, this.salt, hashIterations, hashLength, digest, (err, derivedKey) => {
console.error(err);
this.hashedPassword = derivedKey;
});
};
From the documentation and tutorials online I understood that crypto will convert the string of my salt to a buffer by itself, but this error makes me think otherwise.
Am I missing any steps in using pbkdf2 maybe?
I'm getting the error while trying to create an admin user in the setup :
const admin = new UserCredentials();
admin.username = 'admin';
admin.setPassword('admin');
admin.save();
Links to source code in Github:
Schema
Set the admin
If you call randomBytes (I assume it is crypto.randomBytes) with a callback, then the process is made asynchronously. So when pbkdf2 is called, this.salt hasn't been initialized yet.
Either move the call to pbdkf2 inside the randomBytes' callback, or use the implicitly synchronous version:
try {
this.salt = randomBytes(saltLength);
} catch (err) {
// handle err here
}

SyntaxError: Unexpected token function in async function?

Hi everyone I'm beginner in Nodejs and mongoose.I have tried to insert and retrieve the data in mongoose.I'm using async await function to execute one by one (sequence).can anyone help me? Thanks in advance....
i.e: I want to execute (Async await)concept (SEQUENCE STEP)
1.connect the db
2.create the user
3.find the user.
I'm getting the error :
async function calltaskone(){
^^^^^^^^
SyntaxError: Unexpected token function
at Object.exports.runInThisContext (vm.js:78:16)
at Module._compile (module.js:543:28)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.runMain (module.js:605:10)
at run (bootstrap_node.js:420:7)
at startup (bootstrap_node.js:139:9)
at bootstrap_node.js:535:3
Code for your reference:
'use strict';
const mongoose=require('mongoose');
const calldbconnect=()=>{
return new Promise((resolve,reject)=>{
if(true){
mongoose.connect('mongodb://vdsd:vdwdwh12dw3,#ds11dwdw.mlab.com:1w5664/vorganisation',{useNewUrlParser:true},(err,db)=>{
if(err){
console.log(err);
reject('Db is not connected');
}
else{
resolve('Db is connected');
}
});
}
});
}
const schemadesign=new mongoose.Schema({
clientName:String,
clientId:Number,
clientAddress:String
});
const modeldata=mongoose.model('clientInfo',schemadesign);
const data=[{
clientName:'VIGNESH Mack',
clientId:4128,
clientAddress:'UK'
},{
clientName:'VIGNESH Tokyo',
clientId:4988,
clientAddress:'USA'
}];
function calldatasave(){
return new Promise((resolve,reject)=>{
modeldata.create(data,(err,a,b)=>{
if(err){
reject(`Error occured while data saved ${err}`);
}
else{
resolve('Data saved successfully');
}
});
});
}
const calldatafind=()=>{
return new Promise((resolve,reject)=>{
if(true){
console.log('try to find');
modeldata.find({'clientId':4988},(err,data)=>{
if(err){
reject(`Error occured while find data: ${err}`)
}
else{
console.log(data);
resolve('Data found');
}
});
}
});
}
async function calltaskone(){
const a=await calldbconnect();
console.log(a);
const b=await calldatasave();
console.log(b);
const c=await calldatafind();
console.log(c);
}
calltaskone();
I believe you're using a older version of Node. Async functions are not supported by Node versions older than version 7.6. You can check here.
If you want to use async/await then you need to transpile using Babel for your node version.
Edit:
As you said you are using v7.3, you can use (from v7.0 to v7.5) the --harmony flag to enable the experimental features. To know more about the flag, check this out: What does `node --harmony` do?

How to read data from console in Node.js?

Actually I have tried one code. This code is working fine but I want to access this information outside of callback function. But i am unable to find solution.
var prompt = require('prompt');
prompt.start();
prompt.get(['username', 'email'], function (err, result) {
console.log('Command-line input received:');
console.log(' username: ' + result.username);
console.log(' email: ' + result.email);
data = result.username;
});
console.log(data);
Here if i'm trying to retrieve print data variable it show's error.
Admins-MacBook-Pro:Basic node programs Sandeep$ node Node3.js
prompt: username: /Users/Sandeep/Desktop/NodeJS/Node example/Basic node programs/Node3.js:22
console.log(data);
^
ReferenceError: data is not defined
at Object.<anonymous> (/Users/Sandeep/Desktop/NodeJS/Node example/Basic node programs/Node3.js:22:13)
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:394:7)
at startup (bootstrap_node.js:149:9)
at bootstrap_node.js:509:3
You could use promise, check docs about promise and newer es 6 Async/ await. With promise you could use something like this:
var prompt = require('prompt');
function getPromt () { return new Promise( (resolve, recect) => {
prompt.start();
prompt.get(['username', 'email'], function (err, result) {
console.log('Command-line input received:');
console.log(' username: ' + result.username);
console.log(' email: ' + result.email);
resolve( result.username);
});
});
}
getPromt().then(data =>
console.log('After promise ' + data), ()=>{});
"You won't be able to access that variable outside the callback function. The reason is, the Node.js has a special feature of passing a callback function as the next block of code to be executed after performing an asynchronous IO task."
Refer to this one: how can find return variable value outside anonymous function in node js mysql query function
You can also check this link to learn how to handle with async flow: http://book.mixu.net/node/ch7.html

Redshift data access from node jdbc

I am getting below error when I try to data from redshift with the below mentioned code
var jdbc = new ( require('jdbc') );
var config = {
libpath: 'C:/Users/ABCD/Desktop/jar/RedshiftJDBC41-1.1.6.1006.jar',
//libs: [__dirname + 'path/to/other/jars.jar'],
drivername: 'com.amazon.redshift.jdbc41.Driver',
url: 'jdbc:redshift://examplecluster.abc123xyz789.us-west-2.redshift.amazonaws.com:5439/dev',
user: 'xxxx',
password: 'xxxxx'
};
jdbc.initialize(config, function(err, res) {
if (err) {
console.log(err);
}
});
var genericQueryHandler = function(err, results) {
if (err) {
console.log(err);
} else if (results) {
console.log(results);
}
jdbc.close(function(err) {
if(err) {
console.log(err);
} else {
console.log("Connection closed successfully!");
}
});
};
jdbc.open(function(err, conn) {
if (conn) {
// SELECT statements are called with executeQuery
jdbc.executeQuery("select * from information_schema.tables", genericQueryHandler);
}
});
Error:
C:\Users\ABCD> node redshift.js
C:\Users\ABCD\node_modules\jdbc\lib\jdbc.js:62>
if(this._props.getPropertySync('user') === undefined){>
^ TypeError: undefined is not a function
at JDBCConn.initialize
(C:\Users\ABCD\node_modules\jdbc\lib\jdbc.js:62:20)
at Object.<anonymous>
(C:\Users\ABCD\Desktop\AngularJS\redshift.js:15:6)
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 Function.Module.runMain (module.js:501:10)
at startup (node.js:129:16)
at node.js:814:3
Could you please let me know whether there is nay issue with the above mentioned node jdbc usage for redshift?
Please be aware that this answer applies to node-jdbc 0.0.15 and earlier only. It will not work for node-jdbc 0.1.1 or later, as the API has been completely reworked and is not backwards-compatible.
Try replacing the two lines in your configuration
user: 'xxxx',
password: 'xxxxx'
with
properties: [
['user', 'xxxx'],
['password', 'xxxxx']
]
I got the same error as you attempting to use Node to connect to a local Oracle XE database. After making the change above I was able to connect. I don't believe the error you are getting is specific to RedShift - I believe it affects all databases.
Note that the properties above have to be specified as an array of 2-element arrays. An object such as the following would seem the obvious way to specify the properties, but it doesn't work:
// Don't do this, it doesn't work.
properties: {
user: 'xxxx',
password: 'xxxxx'
}
To be honest, the fix I've proposed above is a workaround. I only found it by reading the source of the jdbc module. I can't say I'm terribly impressed with this module, what with the example code given in the documentation not working, and with a somewhat counter-intuitive and undocumented format for specifying custom properties.

Resources