I have the following compiled typescript class in file: User.js
"use strict";
var mongo = require('mongoose');
var User = (function () {
function User(data) {
this.Name = data.name;
this.City = data.city;
this.State = data.state;
}
User.prototype.nameUpperCase = function () {
return this.Name.toUpperCase();
};
return User;
}());
exports.User = User;
var schema = new mongo.Schema({
Name: String,
City: String,
State: String
});
schema.method('nameUpperCase', User.prototype.nameUpperCase);
var Users = mongo.model('User', schema);
usertest.js contents:
require('User.js'); <-- no matter what I put here
var u1 = new Users({Name: 'Matthew Brown', City:'Austin',State:'TX'});
var u2 = new Users({Name: 'Jonathan Andrews', City:'Georgetown',State:'TX'});
var u3 = new Users({Name: 'Mom(Rose Brown)', City:'Holiday Island',State:'AR'});
var u4 = new Users({Name: 'Ditto(Bill Brown Jr.)', City:'Charlton',State:'MA'});
Users.create(u1,function(err, u1) {
if (err) {
console.log(err);
} else {
console.log("User %s created",u1.Name);
}
});
Users.create(u2,function(err, u2) {
if (err) {
console.log(err);
} else {
console.log("User %s created",u2.Name);
}
});
Users.create(u3,function(err, u3) {
if (err) {
console.log(err);
} else {
console.log("User %s created",u3.Name);
}
});
Users.create(u4,function(err, u4) {
if (err) {
console.log(err);
} else {
console.log("User %s created",u4.Name);
}
});
I have tried everything and i keep getting the error from node saying that it can not find the module 'User' or above, it will say it can not find 'User.js'.
In User.js you are not exporting mongoose User Model
Change
var Users = mongo.model('User', schema);
to
exports.Users = mongo.model('User', schema);
Also in usertest.js, Users not defined anywhere
Change
require('User.js');
to
var Users = require('./User.js').Users; // check for relative path here
Now
can not find 'User.js'
is because you are not setting relative path.
You can refer without relative path to node_modules folder libraries, inbuilt node.js libraries & Global libraries
Related
So, I am making an app with react native and i am trying to use mongoose and mongoDB for my DataBase but i am running into this error: OD.findOne is not a function, OD being my model file.
const mongoose = require("mongoose");
const newOrgData = new mongoose.Schema({
author: String,
PW: String,
name: String,
Good: Number,
Bad: Number,
Medium: Number
});
module.exports = new mongoose.model("OrganizationData", newOrgData)
My DB.js file where i do the function:
const OD = require("../config/OrgData");
export async function GetStats(txt, point) {
await OD.findOne({
name: txt
}, (err, data) => {
if (txt.length <= 3) return Alert.alert("Please use a valid organization, the name needs to be over three characters long.");
if (err) console.log(err);
if (!data) {
Alert.alert("Sorry, that organization does not exist.");
return;
} else {
if (point == 1) {
data.Good++;
data.save();
} else {
if (point == 2) {
data.bad++;
data.save();
} else {
if (point == 3) {
data.medium++;
data.save();
} else {
if (point == 0) {
return Alert.alert("Please choose how you feel about this organization today.");
} else {
Alert.alert("Succes, thank you for your interest.");
}
}
}
}
}
});
}
My server.js file where i connect to mongoose:
const Config = require("./config/config.json");
const mongoose = require("mongoose");
mongoose.connect("mongodb+srv://BlueSyntax:" + Config.Mongo_C_PW +
"#org-qjoao.mongodb.net/" + Config.DB_Name + "?retryWrites=true&w=majority", {
useMongoClient: true
});
How should i fix this?
You have to omit new keyword when exporting the model. The correct form:
module.exports = mongoose.model("OrganizationData", newOrgData)
The original error say's: Cannot destructure property 'firstime' of 'undefined' or 'null'.
I am developing web-base desktop application for Windows pc using node.js and Electron.
I am trying to persist some data in user data directory, I found the idea and using the same approach in this link.
Writing and fetching data works fine, however the error occurred at the first time of fetching the data.
here is the code for UserPreferences class
const electron = require('electron');
const path = require('path');
const fs = require('fs');
class UserPreferences {
constructor(opts) {
const userDataPath = (electron.app || electron.remote.app).getPath('userData');
this.path = path.join(userDataPath, opts.configName + '.json');
this.data = parseDataFile(this.path, opts.defaults);
console.log(userDataPath);
}
get(key) {
return this.data[key];
}
set(key, val) {
this.data[key] = val;
fs.writeFileSync(this.path, JSON.stringify(this.data));
}
}
function parseDataFile(filePath, defaults) {
try {
return JSON.parse(fs.readFileSync(filePath));
} catch (error) {
return defaults;
}
}
module.exports = UserPreferences;
and here's the function for using the UserPreferences class
function isFirstTime() {
try{
const userAccount = new UserPreferences({
configName: 'fipes-user-preferences', // We'll call our data file 'user-preferences'
defaults: {
user: { firstime: true, accountid: 0, profileid: '' }
}
});
var { firstime, accountid, profileid } = userAccount.get('user');
if (firstime === true) { //check if firstime of running application
//do something
} else {
//do something
}
}catch(err){
console.log(err.message);
}
}
the error occurred on the line where I am checking weather the firstime is true or false.
First of all do not declare a object like var { firstTime, .. } like this. if you do this firstTime will be a property of an anonymous object. That you can never access elsewhere. Check what is the output of userAccount.get('user') function, output contain some object like { firstime: true, accountid: "test", profileid: "test" } then try this. Hope this helps you.
var result=userAccount.get('user');
if(result.firstTime===true){
//your code
}
Here is a version of UserPreferences which will be more natural to use as you write your code. You can create it like you see in isFirstTime.
console.debug(userPreferences[accountId]);
userPreferences[accountId] = 1;
This is preferred because there is no reason for a developer not to treat UserPreferences as an object. Another good idea would be separating the writing to the file into a separate flush method, in case you are updating preferences often.
const electron = require("electron");
const fs = require("fs");
const path = require("path");
class UserPreferences {
constructor(defaultPrefs, pathToPrefs) {
const app = electron.app || electron.remote.app;
this.pathToPrefs = path.join(app.getPath("userData"), pathToPrefs + ".json");
try {
this.store = require(this.pathToPrefs);
}
catch (error) {
this.store = defaultPrefs;
}
return new Proxy(this, {
get(target, property) {
return target.store[property];
},
set(target, property, value) {
target.store[property] = value;
fs.writeFileSync(target.pathToPrefs, JSON.stringify(target.store));
}
});
}
}
module.exports = UserPreferences;
Here is a pure version of isFirstTime, that should do what you want, while maintaining a more robust method of checking for isFirstTime. The check can also be changed so check whether lastSignIn is equal to createdAt (with appropriate defaults, of course).
function isFirstTime() {
const account = new UserPreferences({
user: {
accountId: 0,
createdAt: new Date(),
lastSignIn: null,
profileId: ""
}
}, "fipes-user-preferences");
const {lastSignIn} = account;
return lastSignIn === null;
}
I am building a node application, and trying to neatly organize my code. I wrote a serial module that imports the serial libs and handles the connection. My intention was to write a basic module and then reuse it over and over again in different projects as needed. The only part that changes per use is how the incoming serial data is handled. For this reason I would like to pull out following handler and redefine it as per the project needs. How can I use module exports to redefine only this section of the file?
I have tried added myParser to exports, but that gives me a null and I would be out of scope.
Handler to redefine/change/overload for each new project
myParser.on('data', (data) => {
console.log(data)
//DO SOMETHING WITH DATA
});
Example usage: main.js
const serial = require('./serial');
const dataParser = require('./dataParser');
const serial = require('./serial');
//call connect with CL args
serial.connect(process.argv[2], Number(process.argv[3]))
serial.myParser.on('data',(data) => {
//Do something unique with data
if (dataParser.parse(data) == 0)
serial.send('Error');
});
Full JS Module below serial.js
const SerialPort = require('serialport');
const ReadLine = require('#serialport/parser-readline');
const _d = String.fromCharCode(13); //char EOL
let myPort = null;
let myParser = null;
function connect(port, baud) {
let portName = port || `COM1`;
let baudRate = baud || 115200;
myPort = new SerialPort(portName, {baudRate: baudRate})
myParser = myPort.pipe(new ReadLine({ delimiter: '\n'}))
//Handlers
myPort.on('open', () => {
console.log(`port ${portName} open`)
});
myParser.on('data', (data) => {
console.log(data)
});
myPort.on('close', () => {
console.log(`port ${portName} closed`)
});
myPort.on('error', (err) => {
console.error('port error: ' + err)
});
}
function getPorts() {
let portlist = [];
SerialPort.list((err, ports) => {
ports.forEach(port => {
portlist.push(port.comName)
});
})
return portlist;
}
function send(data) {
myPort.write(JSON.stringify(data) + _d, function (err) {
if (err) {
return console.log('Error on write: ', err.message);
}
console.log(`${data} sent`);
});
}
function close() {
myPort.close();
}
module.exports = {
connect, getPorts, send, close
}
The problem is that a module is used where a class or a factory would be appropriate. myParser cannot exist without connect being called, so it doesn't make sense to make it available as module property, it would be unavailable by default, and multiple connect calls would override it.
It can be a factory:
module.exports = function connect(port, baud) {
let portName = port || `COM1`;
let baudRate = baud || 115200;
let myPort = new SerialPort(portName, {baudRate: baudRate})
let myParser = myPort.pipe(new ReadLine({ delimiter: '\n'}))
//Handlers
myPort.on('open', () => {
console.log(`port ${portName} open`)
});
myParser.on('data', (data) => {
console.log(data)
});
myPort.on('close', () => {
console.log(`port ${portName} closed`)
});
myPort.on('error', (err) => {
console.error('port error: ' + err)
});
function getPorts() {
let portlist = [];
SerialPort.list((err, ports) => {
ports.forEach(port => {
portlist.push(port.comName)
});
})
return portlist;
}
function send(data) {
myPort.write(JSON.stringify(data) + _d, function (err) {
if (err) {
return console.log('Error on write: ', err.message);
}
console.log(`${data} sent`);
});
}
function close() {
myPort.close();
}
return {
myParser, getPorts, send, close
};
}
So it could be used like:
const serial = require('./serial');
const connection = serial(...);
connection.myParser.on('data',(data) => {
//Do something unique with data
if (dataParser.parse(data) == 0)
connection.send('Error');
});
I have the following case, when deleting any data, I need to delete the app badges (at the moment I delete them using silent push notication and reduce the app badges number with the cloud function) if the user who sent the request has deleted. But since the user who deleted could send several requests to different users in different places, so I decided that I need to create a function that will be called in firebase database trigger functions and also it will help not to duplicate the same code everywhere .
The function will be approximate such
function adminRemoveAppBadge(userID, dataID, categoryID) {
};
And for example, call it in this function
module.exports = functions.database.ref('/cards/{cardID}/interestedUsers/{interestedUserID}').onWrite(event => {
const currentData = event.data.current;
const prevData = event.data.previous;
const cardID = event.params.cardID;
const interestedUserID = event.params.interestedUserID;
if (currentData.val() && !prevData.val()) {
// value created
return console.log('cardInterestedUserHandler - created');
} else if (!currentData.val() && prevData.val()) {
// value removed
console.log('cardInterestedUserHandler - removed', currentData.val());
const cardRef = admin.database().ref("cards").child(cardID);
const cardRefPromise = cardRef.once("value", function(snap, error) {
if (error) {
return error;
};
if (snap.val()) {
const cardJSON = snap.val();
const cardOwnerID = cardJSON["ownerID"];
if (cardOwnerID) {
const cardOwnerAppBadgesRef = admin.database().ref("userAppBadges").child(cardOwnerID).child("appBadgeModels").orderByChild("dataID").equalTo(cardID);
const cardOwnerAppBadgesRefPromise = cardOwnerAppBadgesRef.once("value", function (cardOwnerAppBadgesRefSnap, error) {
if (error) {
return error;
};
if (cardOwnerAppBadgesRefSnap.val()) {
var deletingPromises = [];
cardOwnerAppBadgesRefSnap.forEach(function(cardOwnerAppBadgesRefSnapChild) {
const appBadgeModelJSON = cardOwnerAppBadgesRefSnapChild.val();
const appBadgeModelID = appBadgeModelJSON["id"];
const senderID = appBadgeModelJSON["senderID"];
if (appBadgeModelID && senderID) {
if (senderID == interestedUserID) {
const cardOwnerAppBadgeRef = admin.database().ref("userAppBadges").child(cardOwnerID).child("appBadgeModels").child(cardOwnerAppBadgeModelID);
const cardOwnerAppBadgeRefPromise = cardOwnerAppBadgeRef.remove();
deletingPromises.push(cardOwnerAppBadgeRefPromise);
// to call
adminRemoveAppBadge
};
} else {
console.log("cardOwnerAppBadgeModelID == null");
};
});
return Promise.all(deletingPromises);
};
});
return Promise.all([cardOwnerAppBadgesRefPromise]);
} else {
return console.log("owner id == null");
};
};
});
return Promise.all([cardRefPromise]);
} else {
return console.log('cardInterestedUserHandler - updated');
};
});
Also functions are in different files. How can I call it in other firebase cloud functions and how do I deploy this function?
Update I tried to do so one of the options as written here and here, but when I tried to do deploy I got an error Cannot find module 'AppBadges/adminRemoveAppBadge.js'.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
exports.adminRemoveAppBadge = function (userID, dataID, categoryID) {
console.log("adminRemoveAppBadge nil");
};
Requested this function so
var adminRemoveAppBadgeModule = require("AppBadges/adminRemoveAppBadge.js");
and call this functions so
adminRemoveAppBadgeModule.adminRemoveAppBadge(cardOwnerID, cardID, 0);
Google Functions are just JS - so normal routes to include code work.
I place my "library" functions in a folder /lib
So my functions folder looks like this:
/functions
/lib
BuildImage.js
SendEmail.js
index.js
package.json
...etc...
within my index.js I just include my code:
const SendMail = require('./lib/SendMail')
const sendMail = new SendMail({
database: db,
mailgun: mailgun
})
exports.sendContactUsMessage = functions.database.ref('/contact-messages/{itemId}').onWrite(sendMail.send(event))
EDIT Added /lib/SendMail.js code:
module.exports = class SendMail {
constructor(config) {
if (!config) {
throw new Error ('config is empty. Must pass database and mailgun settings')
}
if (!config.database) {
throw new Error('config.database is empty. Must pass config.database')
}
if (!config.mailgun) {
throw 'config.mailgun is empty. Must pass config.mailgun'
}
this.database = config.database
this.mailgun = config.mailgun
}
sendEmail (emailData) {
return new Promise((resolve, reject) => {
this.mailgun.messages().send(emailData, (error, body) => {
if (error) {
if (debug) {
console.log(error)
}
reject(error)
} else {
if (debug) {
console.log(body)
}
resolve(body)
}
})
})
}
...
}
I have the following strange situation. I've started writing map/reduce jobs for MongoDB. I now have code (see Map/Reduce/Finalize functions in code below) that is working, except for the "finalize" step. The same code, ran through the mongo shell is producing the expected results (file_count field is added to the result, based upon arraylength. Both JS and Shell command populate the files_per_disc collection equally (files array, per disc, contains the same results). I already tried setting jsMode to true/false.
Any help / Suggestions?
Thanks!!
Sander
var mongojs = require('mongojs');
var db = mongojs('mongodb://super.local/sha', ['files', 'files_per_disc']);
db.on('error', function(err) {
console.log('database error', err)
})
db.on('connect', function() {
console.log('database connected')
})
var files_per_disc = {};
files_per_disc.execute = function() {
console.log('execute');
var mapper = function() {
var key = this.disc; // Disc
var mapObject = {
files: [this.filename]
};
if (this.filesize > 5000000000) {
emit(key, mapObject);
}
};
var reducer = function(key, values) {
var reducedObject = {
files: []
};
values.forEach(function(value) {
value.files.forEach(function(item) {
if (reducedObject.files.indexOf(item) == -1) {
reducedObject.files.push(item);
}
});
});
return reducedObject;
};
var finalizer = function(key, reducedObject) {
if (reducedObject.files) {
reducedObject.file_count = reducedObject.files.length;
}
return reducedObject;
};
db.files.mapReduce(
mapper,
reducer, {
jsMode: false,
out: 'files_per_disc',
finalize: finalizer
},
function(err, result) {
if (err) {
return console.log(err)
};
return console.log(result);
}
);
};
module.exports = files_per_disc;