var db = new Dexie(app.settings.unpublishedBooksDb);
db.version(1).stores({
friends: "++id,name,shoeSize"
});
db.open();
db.close();
I have a precreated indexedDB database using the code above, and then on another view in the application, I need to add a row to a table.
var db = new Dexie('myDb');
db.open().then(function() {
console.log ('opened'); //this works
db.friends.add({name:"Fredrik"}); //this doesnt do anything and adding a catch doesn't throw an error either
}).finally(function () {
db.close();
});
I tried using .transaction but still the same. If I try using Chrome's console, I get an error : Cannot read property add of undefined
your second db instance contains no info about what tables it would contain. So the implicit table property (db.friends) is not there. What actually happens is that it throws TypeError: cannot read property 'add' of undefined. If you would catch the call (not just do a finally), you would get that TypeError catched.
What you can do is to reference the friends table by db.table('friends').add ({name: 'Fredrik'}) instead of db.friends.add({name: 'Fredrik'}).
Beware though that defining the database without specifying table schema is not as thorowgly tested and used, so I would recommend using it with a schema defined to avoid other pitfalls as well. If you for architectural reasons still need to do it your way, be aware that transaction scopes works a little different since you cannot use the dynamic implicit tale properties in the transaction scopes either and db.table() currently does not return a transaction-bound Table instance if you are in a transaction scope. You would have to use the old transaction API:
db.transaction('rw', 'friends', function (friends, trans) {
friends.put({name: 'Fredrik'});
});
...instead of:
db.transaction('rw', 'friends', function () {
db.friends.put({name: 'Fredrik'});
});
Best wishes,
David
Related
i'm experemeting with discord bot and tried to create record in database, but there's some troubles with it.
mongodb server is running and fully functioning.
there's two files.
first, with code of command:
https://sourceb.in/6834bfe20e.js
and second. with mongoose scheme:
https://sourceb.in/9f0c7858df.js
acrually, there's third file index file with command handler and
librarys initializations, but that's does not participate in the error.
I expected to create a record in the database, but there's error what says:
'token is not constructor' in command file:13:19
Problem:
Simply put, you're declaring a constant token, but also passing a parameter named token into your callback. When you're attempting to construct a new object based on the constant, you're actually using the callback's token variable.
Take note of this example, which emits the same error with your setup:
const token = class {
constructor(guild) {
this.guild = guild;
}
};
console.log(new token('1234')); // Works fine.
function foo(token) {
console.log(new token('1234')); // Throws error.
}
foo({ someOtherVar: true });
Solution:
A quick rename of your variable(s) will do. I'd suggest naming your const tokenSchema to avoid conflict (and confusion).
I am having troubles with some parts of my code randomly.
This object is declared in a angular controller.
this.tData = {
'questions':[],
'typeQuestion':[],
'category':[],
'dName':this.dName,
'tCodigo':this.tCodigo}
Then I got some data from others functions and push it into respective fields,
this.tData.questions.push(this.idQuestion) // this come from frontend ng-model
this.tData.typeQuestion.push(this.typeQuest) // this come from frontend ng-model
this.tData.category.push(this.idCategory)// this come from frontend ng-model
This construct my object fine. Doing console.log(this.tData) show me the object completely fine. But then when I pass it to the backend in this function of the angular service.
this.updateStuff = function(codStuff,tData){
return $http.put('/updateStuff' + codStuff,tData)}
The object that backend get doing console.log(params) is
{
questions:['exampleId'],
typeQuestion:['exampleData'],
category:[], // HERE IS THE PROBLEM
dName:'exampleName',
tCodigo:'exampleCod'}
Like you see category:[] is empty but doing console.log(tData) in the service of angular before I send it I see the correct data there.
I miss data when I send it to the backend. This problem happend to me in 3 others cases like this.
Why some arrays are ok in backend and why others are not?
I tried a lot of things but ever 1 item of the object I send to the backend go empty.
If you need more specific code tell me in comments.
Updates
Code here I push category in the controller:
this.getCategoryByName = function(){
this.bName = document.getElementById('seCategory').value;
Category.getCategoryByName(this.bName).then((result)=>{
this.idCategory = result.data.data._id; // this give me id of category
this.tData.category.push(this.idCategory);
})
}
2
This is where I call in frontend my functions:
<button class="btn btn-primary" ng-click="ctController.getCategoryByName(); ctController.updateTest();" > up </button>
This is the code of updateTest() function:
this.updateTest = function(){
Test.updateTest(this.codTest,this.tData).then(result=>{})
}
Above method call the angular service updateStuff
SOLVED
Solved adding a chain promise in the method getCategoryByName and adding the updateTest() method nested in getCategoryByName() method more or less like #T.J. Crowder sugest so I give it the response.
Code here I push category in the controller:
this.getCategoryByName = function(){
this.bName = document.getElementById('seCategory').value;
Category.getCategoryByName(this.bName).then((result)=>{
this.idCategory = result.data.data._id; // this give me id of category
this.tData.category.push(this.idCategory);
})
}
That tells us that you're calling updateStuff before Category.getCategoryByName has finished its work, and so before this.tData.category.push is called. The reason console.log seems to show you things in this.tData.category is (as I mentioned in a comment) because of deferred evaluation in the console.
This also explains why it happens sometimes: You have a race between that Category.getCategoryByName operation and the operation calling updateStuff. Sometimes, Category.getCategoryByName wins and so updateStuff includes the pushed information, other times the code calling updateStuff wins and so updateStuff doesn't have the information in this.tDate.category (yet).
this.getCategoryByName should return the promise chain:
this.getCategoryByName = function(){
this.bName = document.getElementById('seCategory').value;
return Category.getCategoryByName(this.bName).then((result)=>{
// ^^^^^^
this.idCategory = result.data.data._id; // this give me id of category
this.tData.category.push(this.idCategory);
});
};
...and then you should make whatever is calling updateStuff dependent on the resolution of that promise.
(You'll also want to ensure that something handles the chain's rejection path. Your current getCategoryByName ignores errors, which will lead to "Unhandled rejection" errors in the console if Category.getCategoryByName fails.)
I'm trying to put dynamically function call in Node.js in order to avoid a infinite list of switch-case.
Here a instance of file I want to reach :
var Object = require('../models/Object'); // it's a classic mongoose Schema's object
Here my dynamic function :
/***** post words *****/
router.post('/words', function (req, res) {
var word = req.body ;
var Theme = req.body.theme
[Theme].add[Theme](word, function(err, words) {
if(err) {
res.json(err);
throw err;
}
return res.json(words);
})
})
We suppose a case where the object.name is "Object".
The function I want to build have to call an addPost method in an another file. In order to dynamically call this files I have prepared a computed name property mechanism. Hence I always call the file corresponding to my need. If I have required Object and the user post with a Object's category value, okay it will go on the Object file to compute the Post toward the good destination. So my computed name property look as following :
console.log(req.body.name) // > "Object"
Name = req.body.name
console.log(Name) // > "Object"
Okay now,
When I enter explicitly the name of the object to cal the function, as following :
Object.functionObject()
the function works fine.
BUT if I use a dynamically value call, like :
[Name].functionOf[Name]()
the function returns me :
TypeError: Cannot read property of undefined
Also,
I have try with ${Name} but my console returns me :
TypeError: console.log(...) is not a function
I have tried to install ES6 on Node.js's side sames result for now.
How it is possible since the console.log return me the great value ?
[Theme].add[Theme]()
This code creates an array with Theme as the first value and then calls functionOf, which doesn't exist on the array type. addTheme is actually a syntax error, but the engine never reaches it.
Although I recommend using a switch, I think what you're trying to do is something like this
// define Object1, Object2 with functionObject()
var objectCollection = {};
objectCollection[Object1.name] = Object1;
objectCollection[Object2.name] = Object2;
// Then you get req.body.name later
var objectName = req.body.name;
// and call the method
objectCollection[objectName].functionObject()
This will technically work, but there are a lots of failure possibilities and relying on reflection in this way makes me nervous because your client needs to know the inner workings (object and function names for instance). This is bad.
If the behavior of these objects is that different you should probably separate these into separate routes and let your client decide which it needs if you're making an api.
You could also create a factory to return the proper object and bury the switch statement there.
I am assuming Object contains all those methods
router.post('/words', function (req, res){
var word = req.body ;
var Theme = req.body.theme; // Post
// Object.addPost();
Object[`add${Theme}`](word, function(err, words) {
if(err){
res.json(err) ;
throw err;
}
return res.json(words);
});
// if you want Object.Post.addPost then
Object[Theme][`add${Theme}`](word, function(err, words) {
if(err){
res.json(err) ;
throw err;
}
return res.json(words);
});
});
Problem
Node.js MongoDB library consistently returns undefined for collection.count({}). This question has been posted and answered numerous times, and I've been sure to go through all previous solutions, but none seem to work, and I always get undefined.
As a background to the question, I am making a Job Automator, and before adding a new job, I want to make sure that 0 records already exist in the database that have the same name as the new job being added (i.e. names are unique). EDIT: There are a few cases where I do want to allow duplicates, so I don't want using indexing and dis-allow duplicates at the DB level.
Code
In this case, the console.log() inside count just prints undefined. In this case, I have put in an empty query string as part of debugging (not currently testing for name collisions).
add: function(io, newJob)
{
//mc is where require('mongodb').MongoClient is saved
//connectionString contains a valid connection string
//activeCollection contains the name of the collection
//(I am sure mc, connectionString and activeCollection are valid)
//I know this as I have used them to insert documents in previous parts
mc.connect(connectionString, function(err,db)
{
if(err)
throw err;
else
{
db.collection(activeCollection, function(err,collection)
{
if(err)
throw err;
//Start of problematic part
//See also "What I've tried" section
collection.count({},function(err,count)
{
console.log(count);
});
//End of problematic part
//Omitting logic where I insert records for brevity,
//as I have confirmed that works previously.
});
}
db.close();
});
}
What I've tried
I've read the previous questions, and replaced the content between //Start of problematic part and //End of problematic part in the previous code block with the following blocks:
Fully breaking out the callback (also prints undefined):
function countDocs(callback)
{
collection.count({},function(err, count)
{
if(err)
throw err;
callback(null, count);
}
}
countDocs(function(err,count)
{
if(err)
throw err;
console.log(count);
});
I've even tried things I know wouldn't work
var count = collection.count({});
NEW (1/28/16)
It was a little sloppy of me to not check the error in my count(), so I added a if(err)console.log(err); into the count() block and it turns out the error is:
{ [MongoError: server localhost:27017 sockets closed]
name: 'MongoError',
message: 'server localhost 27017 sockets closed' }
Which I don't really understand because in other sections of code, I am able to use the same connect() and collection() calls and make inserts into the DB just fine. Any insight based on this?
Any help would be much appreciated!
Let's deal with the intent of the question:
I am making a Job Automator, and before adding a new job, I want to
make sure that 0 records already exist in the database that have the
same name as the new job being added (i.e. names are unique).
Rather than labor through javascript, just set a unique index on the name key. In mongo:
db.collection.ensureIndex( { name: 1 }, { unique: true } )
Then when you insert a document use a try/catch block to catch any attempt to create a document with a duplicate name.
You can use collection.find().toArray(function(err,documents) { ...});, which returns an empty array if no documents match your query. Checking the length property of the array should be equivalent to what you are trying to achieve with count().
More info in the docs: https://mongodb.github.io/node-mongodb-native/api-generated/cursor.html#toArray
I am returning a Mongoose document and wish to add some meta data to it before I send it off. I am however unable to add any properties and I am not sure why. I have checked that it is extensible with Object.isExtensible(doc) and it is.
Item.findById(req.params.id).exec(function(err, doc) {
doc.blah = 'hello';
console.log(doc); // No trace of 'blah'. I can change/delete existing props however
})
What could be issue?
Ah.. My object is a Mongoose document which doesn't allow adding properties. The solution is to either convert the returned document to a plain object or to call lean() in the query.
Item.findById(req.params.id).exec(function(err, doc) {
var obj = doc.toObject();
...
});
Item.findById(req.params.id).lean().exec(function(err, doc) {
...
});