MongoError : selector must be a valid JavaScript object - node.js

I am using mongodb driver for nodejs.
I am getting below error while updating a record.
{"name":"MongoError","message":"selector must be a valid JavaScript
object","driver":true}
Here is my script :
MongoClient.connect(url, function (err, db) {
if (err)
{
console.log('Unable to connect to the mongoDB server. Error:', err);
return;
}
var collName = "bank";
var SelectParas = {"name":"ABC"};
var UpdateValues = {"name":"PQR"};
db.collection(collName).update(collName,SelectParas,{$set:UpdateValues},function (err,numUpdated){
if(err)
{
console.log('err');
console.log(err);
return;
}
if(numUpdated)
{
console.log('Updated Successfully %d document(s).', numUpdated);
}
db.close();
});
});
I can write the below line in mongo console & it works.
db.bank.update({"name":"ABC"},{$set:{"name":"PQR"}})

You are passing collecion name i.e. a string as find query of the update. Need not pass collecton name there.
db.collection(collName).update(collName,SelectParas,{$set:UpdateValues},function (err,numUpdated)
// collName need not pass in the update function.
Need to use
db.collection(collName).update(SelectParas,{$set:UpdateValues},function (err,numUpdated) instead.

Related

sqlite3 create database with callback using Node

I've searched on how to create a sqlite3 database with a callback in Node.js and have not been able to find any links. Can someone point me towards documentation or provide a 2-3 line code sample to achieve the following:
Create a sqlite3 database and catch an error if the creation fails for any reason.
Here is what I've tried:
let dbCreate = new sqlite3.Database("./user1.db", sqlite3.OPEN_CREATE, function(err){
if(!err){
logger.infoLog("Successfully created DB file: " + dbFileForUser + " for user: " + username );
} else {
logger.infoLog("Failed to create DB file: " + dbFileForUser + ". Error: " + err );
}
});
dbHandler[username] = dbCreate;
When I execute this, I get the following error:
"Failed to create DB file: ./database/user1.db. Error: Error: SQLITE_MISUSE: bad parameter or other API misuse"
This call without callback works just fine.
var customDB = new sqlite3.Database("./custom.db", sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE);
But in this, I will not know if I run into any errors while creating the Database.
Try this:
let userDB = new sqlite3.Database("./user1.db",
sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE,
(err) => {
// do your thing
});
Example.
#Irvin is correct, we can have a look at http://www.sqlitetutorial.net/sqlite-nodejs/connect/ and
check it says if you skip the 2nd parameter, it takes default value as sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE
and in this case if database does not exist new database will be created with connection.
sqlite3.OPEN_READWRITE: It is to open database connection and perform read and write operation.
sqlite3.OPEN_CREATE : It is to create database (if it does not exist) and open connection.
So here is the first way where you have to skip the 2nd parameter and close the problem without an extra effort.
const sqlite3 = require("sqlite3").verbose();
let db = new sqlite3.Database('./user1.db', (err) => {
if (err) {
console.error(err.message);
} else {
console.log('Connected to the chinook database.|');
}
});
db.close((err) => {
if (err) {
return console.error(err.message);
}
console.log('Close the database connection.');
});
And this is the 2nd way to connect with database (already answered by #Irvin).
const sqlite3 = require("sqlite3").verbose();
let db = new sqlite3.Database('./user1.db', sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE
, (err) => {
if (err) {
console.error(err.message);
} else {
console.log('Connected to the chinook database.');
}
});
db.close((err) => {
if (err) {
return console.error(err.message);
}
console.log('Close the database connection.');
});

Serverless - AWS Lamda with MongoDB Atlas Queries Not Running

I've created an AWS account and want to use MongoDB Atlas with AWS Lambda.
The only dependency I've downloaded is mongodb locally.
npm install mongodb
Driver based connection string given from mongoDB Atlas for Nodejs is
var uri = "mongodb+srv://kay:myRealPassword#cluster0.mongodb.net/test";
MongoClient.connect(uri, function(err, client) {
const collection = client.db("test").collection("devices");
// perform actions on the collection object
client.close();
});
I think the connection is successful, because err parameter is NULL.
But I cannot figure out how to create collection, how to find results, how to insert documents.
I've tried this code
module.exports.hello = (event, context, callback) => {
var MongoClient = require('mongodb').MongoClient;
var uri = "mongodb+srv://kay:myRealPassword#cluster0.mongodb.net/test";
MongoClient.connect(uri, function(err, client) {
const collection = client.db("test").collection("devices");
collection.insert( { "msg" : "My First Document" } );
var results = client.db("test").collection("devices").find();
console.log(results);
client.close();
callback(null, { message: 'Go Serverless v1.0! Your function executed successfully!', event });
});
};
but it returns (in Windows console) a huge Object in JSON format, its like a configuration data (not a query result)
enter image description here
I'm executing this code locally by
sls invoke local --function hello
The general idea is to check if there is an error in the connection, the insert, and so on. Take at look at this error checking:
if (error) return 1;
There are more sophisticated methods, but for your case this should do the work.
This is a example of how it show look your script:
MongoClient.connect(uri, (error, client) => {
if (error) return 1; // Checking the connection
console.log('Connection Successful');
var db = client.db('mydb'); // Your DB
let newDocument = { "msg" : "My First Document" }; // Your document
db.collection('mycollection').insert(newDocument, (error, results) => { // Your collection
if (error) return 1; // Checking the insert
console.log('Insert Successful');
})
db.collection('mycollection')
.find({})
.toArray((error, accounts) => {
if (error) return 1; // Checking the find
console.log('Find Successful');
console.log(accounts);
return 0;
})
})
And you should have an output like this:
Connection Successful
Insert Successful
Find Successful
[ { _id: 5a857dd2c940040d85cbe5f2, msg: 'My First Document' } ]
If your output is not like this, well the missing log would point the place where you have your error.

Mongo throwing 'topology was destroyed' error after calling Collection.drop with node.js MongoDB Driverr

Every time when I call the drop collection function with the MongoDB Driver. This error is thrown:
"MongoError: topology was destroyed".
Here is my code:
var dropCollection = function(db){
let collectionA = db.Collection('CollectionA');
collectionA.drop(function(err, delOK) {
if (err) console.log(err);
if (delOK) console.log("Collection deleted");
});
};
MongoClient.connect(connectionUrl, null, function(err, db){
let current_db = db.db(dbName);
dropCollection(current_db);
db.close();
});
I have tried other function like Collection.find. It runs without error. It seems that the error is showing that it lost the connection to the DB.
I am using:
native node driver 2.2.24
MongoDB version 3.4.1
This is because the db.close() was called before the drop() command was executed. It is expected, due to the way node's callback mechanism works.
Assuming the collection CollectionA exists, moving the db.close() into the drop() callback should work as expected:
var dropCollection = function(db){
let collectionA = db.collection('CollectionA');
collectionA.drop(function(err, delOK) {
if (err) console.log('Error here:' + err);
if (delOK) console.log("Collection deleted");
db.close(); // move db.close() here to ensure that
// it's called *after* the drop()
});
};
MongoClient.connect(url, null, function(err, db){
let current_db = db.db(dbName);
dropCollection(current_db);
});
If you see an error like ns not found, then it means that CollectionA doesn't exist.

mongodb in nodejs return undefined when trying to connect to collection

when I write this code below I get:
Connected correctly to DB
undefined
undefined
I have collection named users, so this sould not happened... why is the happening?
Thanks
var url = 'mongodb://user:pass#ds023475.mlab.com:23475/small-talkz';
MongoClient.connect(url, function(err, db) {
if (err) {
console.log(err);
return db.close();
}
console.log("Connected correctly to DB.");
// update a record in the collection
console.log(db.collection("users"));
console.log(db.users);
return db.close();
});
I would say you need to .find() what it is you want from the collection. However, it is strange that it returns undefined. Try this code:
var MongoClient = require('mongodb').MongoClient, format = require('util').format;
MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
if(err) throw err;
db.collectionNames(function(err, collections){
console.log(collections);
});
});
to see what collection names the current database has. Perhaps it doesn't exist?
Otherwise, try finding the collection elements, as shown in the docs example.

Storing Collection result from mongoDB in Node

I am new to node and I have read the data from mongoDB successfully.
But I would like to store the whole data from the Collection into a variable in nodejs as I would like to use them in the index page.
I do not know how to store it.
// Connection URL
var url = 'mongodb://localhost:27017/test';
// Use connect method to connect to the Server
MongoClient.connect(url, function (err, db) {
assert.equal(null, err);
console.log("Connected correctly to server");
seriescollection = db.collection('series');
});
var findseries = function (db, callback) {
var cursor = db.collection('series').find();
cursor.each(function (err, doc) {
assert.equal(err, null);
if (doc != null) {
console.dir(doc);
} else {
callback();
}
});
};
MongoClient.connect(url, function (err, db) {
assert.equal(null, err);
//insertDocument(db, function () {});
findseries(db, function () {
db.close();
});
});
My sample JSON object in MongoDb is
{
"_id" : "b835225ba18",
"title" : "Name",
"imageurl" :"https://promotions.bellaliant.net/files/Images/TMN/Ballers-June2015.jpg",
"namespaceId" : "UNI890"
}
I would like to access all the fields and create a page based on the fields that I have stored. I need to access all the fields and that is my main goal.
This is a pet project I am working on a leisure time to learn MEAN stack a bit.
Thanks a lot for your help!!!!
There's a few issues with this code, but I think what you're looking for is the toArray method:
var findseries = function (db, callback) {
db.collection('series').find().toArray(function(err, allTheThings) {
// Do whatever with the array
// Spit them all out to console
console.log(allTheThings);
// Get the first one
allTheThings[0];
// Iterate over them
allTheThings.forEach(function(thing) {
// This is a single instance of thing
thing;
});
// Return them
callback(null, allTheThings);
}
}
More here: https://docs.mongodb.org/manual/reference/method/cursor.toArray/
And here: https://mongodb.github.io/node-mongodb-native/api-generated/cursor.html#toarray

Resources