I am currently using PouchDB as my DB and I am using Cloudant for the remote service. I am currently trying to create document, however, when I invoke the function, I have errors.
May I know where did I do wrong? Could it be the URL wrong or my syntax is wrong?
Uncaught Reference Error: PouchDB is not a constructor
This is my javascript code
function pouchdb() {
var db = new PouchDB("todos");
var remoteDB = new PouchDB("http://example.cloudant.com/example");
window.PouchDB = db;
var doc = {
"_id": "Can123",
"name": "You123",
"occupation": "See1",
"age": 3,
"hobbies": [
"Watch 9pm show",
"chasing laser pointers",
"lookin' hella cute"
]
};
db.put(doc);
PouchDB.sync(db, remoteDB);
}
HTML code
<button onclick="pouchdb()">pouchdb</button>
Update
I changed my insert code for this set of code
function pouchdb() {
var db = new PouchDB("todos");
var remoteDB = new PouchDB("http://example.cloudant.com/example");
var todo = {
_id: "mittens1233",
title: "hello",
occupation: "kitten123"
};
db.put(todo, function callback(err, result) {
if (!err) {
console.log('Successfully posted a todo!');
}
});
}
The result i got back is Successfully posted a todo!, however, my cloudant dashboard still shows 0 doc. May I know why?
Remove that line
window.PouchDB = db;
I think that's the problem. Once you click the button, the global PouchDB turns the variable db, what makes it not be a constructor anymore.
If the error still continues, #gcampbell comment should be right?
Related
I'm new to Javascript and I'm having a recurring error with a REST API. It's a strange error (for me at least), so strange that I don't know what to call it. I'm calling it "Doubling", but it probably has a proper name, I just don't know what it is.
Anyway, the situation is this. I'm creating a REST API about cars. I'm using Javascript and the following node modules:
1) Express
2) Body-Parser
3) Mongoose
4) MongoDB
5) Mongod
The DB is very simple. It literally just lists the names of cars. Here's the code for it:
var express = require('express');
var bodyParser = require('body-parser');
var theAutos = require('./cardata');
var mongoose = require('mongoose');
var app = express();
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
mongoose.Promise = global.Promise;
var promise = mongoose.connect('mongodb://localhost/car_test_project', {
useMongoClient: true,
});
promise.then(function(db){
console.log('DATABASE NOW CONNECTED!!');
}).catch(function(err){
console.log('CONNECTION ERROR', err);
});
//*****SCHEMA*****
var Schema = mongoose.Schema;
var carTestSchema = new Schema({
name: String,
});
var Car = mongoose.model('Car', carTestSchema);
//*****END SCHEMA*****
//*****CAR DATA 'FOR EACH' FUNCTION*****
theAutos.forEach(function(theAutos){
var newAutomobile = new Car(theAutos);
newAutomobile.save(function (err) {
if (err) {
return (err);
}
});
});
//*****END 'FOR EACH' FUNCTION*****
//******THE 'GET' CODE*****
app.get('/carurl', function(req, res){
console.log(3);
Car.find({}).exec(function(err, car){
console.log(2);
if(err) {
return res.status(500).send(err);
}
return res.json(car);
});
});
//******END THE 'GET' CODE*****
//*****POST COMMAND CODE*****
app.post('/carurl', function(req, res){
var addAnAuto = new Car(req.body);
addAnAuto.save(function(err, car) {
if(err) {
return res.status(500).send(err);
}
return res.status(201).json(car);
});
});
//*****END POST COMMAND CODE*****
app.listen(8000, function(){
console.log('I be listening!');
});
At the beginning, the DB only has one entry; Ferrari. I've put this in a separate file called cardata.js and then I 'require' that file in the 3rd line of the above code (that's what the var theAutos = require('./cardata'); refers to. Here's the code for that file:
module.exports = [
{name: "Ferrari"}
]
As you can see, very simple database with only one entry. Now, here's where things get WEIRD!
I go to Postman and make a GET request. Postman comes back with Ferrari. So far so good. Then I go to make a POST request. I ask for a second car to be added to the database, in this case a Bugatti. I make a second GET request and I see:
{
"_id": "123etc...",
"name": "Ferrari",
"__v": 0
}
{
"_id": "xyzetc...",
"name": "Bugatti",
"__v": 0
}
So it's adding Bugatti to the database. That's great, right? It's doing what it's supposed to.
Wrong!
See, I need to make sure the addition is permanent, right? So I go to my terminal and restart the database by typing node index.js. I then go back to Postman and make yet another GET request. I'm expecting to see just Ferrari and Bugatti, right? However what I actually see, is:
{
"_id": "123etc...",
"name": "Ferrari",
"__v": 0
}
{
"_id": "xyzetc...",
"name": "Bugatti",
"__v": 0
}
{
"_id": "123etc...",
"name": "Ferrari",
"__v": 0
}
WTF?!? Where did that extra Ferrari come from? I certainly didn't want it there. It's like the DB is loading the DB with my POST request and then loading the original DB (which just had Ferrari in it) on top! Hence "Doubling"
Now, you might be thinking, "Shank, you fool! Just use a drop command like Car.collection.drop(); to refresh the DB when you reload it!"
Trouble is, when I try that I lose my Bugatti!
What I need is to figure out a way to (a) Add my Bugatti and other cars to the database and (b) do so in such a way that when I restart the database it doesn't "Double" and add another Ferrari in there.
It's no exaggeration to say I'm absolutely DESPERATE for help at this point. I've been grappling with this for days and I've read countless online tutorials and I've not come up with ANYTHING that can help me.
Any advice you could give would be massively appreciated.
Cheers,
Shank.
Im working with a module known as update-json. Im attempting to update json within a file, im having issues addressing the key I want or what seems to happen is a new entry gets added in a different branch..
My Querykeys.json looks like this
{
"servers": [
{
"netdomain": "google.com",
"netshare": "password",
"authip": "216.58.203.46"
},
{
"netdomain": "localhost",
"netshare": "localghost",
"authip": "127.0.0.1"
},
{
"netdomain": "facebook.com",
"netshare": "timeline",
"authip": "31.13.69.228"
}
]
}
Currently I have the system reading and isolating code just fine, my intenetions are to update a netshare from the code of localhost from localghost to "foo".
The module in question is located here, https://www.npmjs.com/package/update-json.
The code i have setup is exactly like there code is on the website.
var updateJson = require('update-json');
// let's assume the file contains this:
// {aaa: 'bbb', ccc: 'ddd'}
var file_path = './querykeys.json';
var data = {servers: 'xxx', yyy: 'zzz'};
updateJson(file_path, data, function (error) {
if (error) {
throw error;
}
else {
console.log();
}
});
With the type of structure that I have, how can i format var data to independently change localhosts netshare to foo?
Thank you
I am trying to get an Alexa skill (JS/Lambda) to post a value to a REST server using HTTP.request. I am trying to hack together something simple that will get the job done. I think I am missing something obvious.
Ideal Skill Usage
I say, "Alexa, tell Posting Test five."
Alexa updates the value at the URL specified in code to 5.
Alexa says, "I have updated the value to five."
Problems
I have two problems:
Spoken vs. typed utterances. If I type my slot value in the Amazon Service Simulator ("five") the value is posted to my server, as it should be. However, if I speak the same utterance, even though Alexa recognizes the words correctly (confirmed by looking at cards in the app), the value is not posted, and she says, "I can't find the answer to the question."
Where and how to call output function. I think I need to add something like the two lines below, but depending on where I add it in my current code, Alexa either responds without updating the node, or doesn't do anything.
var text = 'I have updated the value to' + targetSlot;
output( text, context );
Invocation Name
posting test
Intent Schema
{
"intents": [ {
"intent": "writeTarget",
"slots": [ {
"name": "Target",
"type": "NUMBER"
} ]
}]
}
Sample Utterances
writeTarget {Target}
AlexaSkill.js and index.js
I am using the AlexaSkill.js file that can be found in each example here.
My index.js looks like this. URL, req.write string, etc., are replaced with ****.
exports.handler = function( event, context ) {
var APP_ID = undefined;
const http = require( 'http' );
var AlexaSkill = require('./AlexaSkill');
var options = {
host: '****.com',
path: '/****',
port: '****',
method: 'PUT'
};
callback = function(response) {
var str = ''
response.on('data', function (chunk) {
str += chunk;
});
response.on('end', function () {
console.log(str);
});
};
var targetSlot = event.request.intent.slots.Target.value;
var req = http.request(options, callback);
req.write("****");
req.end();
};
function output( text, context ) {
var answer = {
outputSpeech: {
type: "PlainText",
text: text
},
card: {
type: "Simple",
title: "System Data",
content: text
},
shouldEndSession: true
};
context.succeed( { answer: answer } );
}
Current Usage: A
I type "five" in the Service Simulator.
Node updates but Alexa doesn't say anything.
Current Usage: B
I tell Alexa, "Tell Posting Test two."
Alexa says, "I can't find the answer to the question." Card confirms she heard me correctly.
Nothing gets updated.
Thanks in advance for any help.
Update: Logs
Updating post to add logs:
Error message
{
"errorMessage": "Process exited before completing request"
}
Log Output Error
TypeError: Cannot read property 'intent' of undefined
at exports.handler (/var/task/index.js:24:35)
Lambda Response
The response is invalid
I'm thinking about making my own JavaScript client library, and I like the way Firebase formats requests. I'm trying to understand whats going on. From looking at the web guide here I found the below code:
var ref = new Firebase("https://docs-examples.firebaseio.com/web/saving-data/fireblog");
var usersRef = ref.child("users");
usersRef.set({
alanisawesome: {
date_of_birth: "June 23, 1912",
full_name: "Alan Turing"
},
gracehop: {
date_of_birth: "December 9, 1906",
full_name: "Grace Hopper"
}
});
I can see that ref is equal to a function called Firebase, and usersRef is equal to ref.child.
I'm imagining something like this:
Firebase = function(url) {
this.child = function(path) {
console.log(url);
console.log(path);
};
};
Here I can see that usersRef.set is being called but I can't figure out how or where this would go? Is set a function or an object? I notice firebase has set(), update(), push() and transaction(), making me think these are functions.
"TypeError: Cannot read property 'set' of undefined
Maybe I'm on the wrong path totally, I'm just not familiar with this pattern.
If you check the Firebase API, you will see that child() returns a new Firebase reference to the child location. So something like this:
var Firebase = function(url) {
console.log(url);
this.child = function(path) {
return new Firebase(url+'/'+path);
};
this.set = function(object) {
console.log(object);
};
};
I've updated you jsbin: https://jsbin.com/nucume/2/edit?js,console
I am attempting to get a list out of my database. The documents look like:
{
"class": "lists",
"collection": "symptoms",
"order": "6",
"en": "Headache",
"_id": "9022034e7d5ecd0efab0762c5b7f0c04"
}
There are an arbitrary number of "collection"s.
A view function simply returns a bunch of objects in the class "lists":
// Emit lists
exports.viewlist = {
map: function(doc) {
if (doc.class === 'lists') {
emit(
doc.collection, {
order: doc.order,
name: doc.en
});
}
}
};
I wrote a list function to try to filter the output to just the list that I want.
exports.viewlist = function(head, req) {
var row;
start({
code: 200,
headers: {
'Content-Type': 'text/json; charset=utf-8',
}
});
while (row = getRow()) {
if (row.collection === req.l) {
send(JSON.stringify(row.value));
}
}
};
CouchDB throws an error when I visit the URL of the list:
http://localhost:5984/dev/_design/emr/_list/viewlists/viewlist?l=symptoms
{"error":"TypeError","reason":"{[{<<\"message\">>,<<\"point is undefined\">>},
{<<\"fileName\">>,<<\"/usr/share/couchdb/server/main.js\">>},
{<<\"lineNumber\">>,1500},\n {<<\"stack\">>,
<<\"(\\\"_design/emr\\\",[object Array],
[object Array])#/usr/share/couchdb/server/main.js:1500\
()#/usr/share/couchdb/server/main.js:1562\
#/usr/share/couchdb/server/main.js:1573\
\">>}]}"}
I can't figure out where I'm going wrong here.
I also ran into this error and what causes it, as hinted at by #Pea-pod here Submitting form to couchDB through update handler not working, is not defining properly your exports in the couchapp's design documents. In our case it was as list function that couldn't be called and instead displayed a 500 error with Type error and point is undefined in the couchdb log.
We use kanso and in the app.js we hadn't required the list file. We had:
module.exports = {
rewrites: require('./rewrites'),
views: require('./views'),
shows: require('./shows')
};
Changing it to the following solved the problem:
module.exports = {
rewrites: require('./rewrites'),
views: require('./views'),
shows: require('./shows')
lists: require('./lists'),
};
Can I suggest to a moderator to change the title of this question to include point is undefined which is the error that shows up in the CouchDB log when this type of error is made, in order to help others find it more easily?