how can i know if connection is safe true? - javascript

i made many times questions about connections on mongodb, i cant understand many things yet, but i try...
with this connection...
db.collection('usuarios').insert(campos,{safe:true}, function(err, result)
i get a safe connection.... but mongodb pull me this warning
========================================================================================
= Please ensure that you set the default safe variable to one of the =
= allowed values of [true | false | {j:true} | {w:n, wtimeout:n} | {fsync:true}] =
= the default value is false which means the driver receives does =
= return the information of the success/error of the insert/update/remove =
= =
= ex: new Db(new Server('localhost', 27017), {safe:true}) =
= =
= http://www.mongodb.org/display/DOCS/getLastError+Command =
= =
= The default of false will change to true in the near future =
= =
= This message will disappear when the default safe is set on the driver Db =
========================================================================================
so i try this way...
var db = mongo.db("root:toor#127.0.0.1:27017/cordoba",{safe:true});
db.collection('usuarios').insert(campos,{new:true}, function(err, result)
but im not sure if this is a safe:true connection so i put like this
var db = mongo.db("root:toor#127.0.0.1:27017/cordoba",{safe:true});
db.collection('usuarios').insert(campos,{safe:true},{new:true}, function(err, result)
may be that way is safe:true but when i put safe:true before new:true mongodb returns me the old var, so i put safe:true after new:true
var db = mongo.db("root:toor#127.0.0.1:27017/cordoba",{safe:true});
db.collection('usuarios').insert(campos,{new:true},{safe:true}, function(err, result)
and works right but im not sure if it is safe:true, so i try put safe:true in new:true object like this
var db = mongo.db("root:toor#127.0.0.1:27017/cordoba",{safe:true});
db.collection('usuarios').insert(campos,{new:true,safe:true},function(err, result)
i thought that mongdb freaks out! but nothing... no error no nothing .... so i dont know how can i know when mongodb is using safe:true or not safe:true...
how can i know that??

the api is no longer {safe: true} but {w: 1} http://mongodb.github.com/node-mongodb-native/api-generated/db.html
var db = mongo.db('mongodb://127.0.0.1:27017/test', {w: 1})
{safe: true} will still work, but it's deprecated. if you set it at the DB level, you don't need to set it at the collection.insert() level.
the api signature for insert is insert(docs[, options][, callback]), so you should only have one options object.
also, there is no {new: true} options for collection.insert.
so basically, you don't need to set any options (on insert).

Related

How to know what parameters are available in a callback function? Javascript, MongoDB

I am a beginner in JavaScript and web development in general. I've been studying by myself and have hit numerous roadblocks along the way.
Right now, I am very confused about functions with callback functions and its parameters. I have read documentations about these but they are currently too high level for me. I just have a few questions based on the two code snippets below.
How do I know what parameters are available in the callback functions? In #1, #2 and #3, they have different second parameters and in #4 it has no second parameter.
Is err argument always in the first parameter when you have more than 1 parameters? Can I choose not not have an err parameter? Can I choose so that err is not the first parameter?
How do I know if a function can have a callback function?
Lastly, I do not understand why in #99.1, callback(result) has an argument of result when the callback function in #99.2 is just function() { client.close() }? Why not just callback()?
Advanced thank you to anyone who will provide an idea about this! Thank you! Any reference, guide or tutorials would be a huge help.
Here are the code sources.
First code snippet source (Insert a Document)
Second code snippet source (collection example)
const MongoClient = require('mongodb').MongoClient;
const test = require('assert');
// Connection url
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'test';
// Connect using MongoClient
MongoClient.connect(url, function(err, client) { <-------------------- #1
// Create a collection we want to drop later
const col = client.db(dbName).collection('createIndexExample1');
// Show that duplicate records got dropped
col.find({}).toArray(function(err, items) { <-------------------- #2
expect(err).to.not.exist;
test.equal(4, items.length);
client.close();
});
});
const insertDocuments = function(db, callback) {
// Get the documents collection
const collection = db.collection('documents');
// Insert some documents
collection.insertMany([
{a : 1}, {a : 2}, {a : 3}
], function(err, result) { <---------------------- #3
assert.equal(err, null);
assert.equal(3, result.result.n);
assert.equal(3, result.ops.length);
console.log("Inserted 3 documents into the collection");
callback(result); <----------------------- #99.1
});
}
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'myproject';
const client = new MongoClient(url, {useNewUrlParser: true});
// Use connect method to connect to the server
client.connect(function(err) { <---------------------- #4
assert.equal(null, err);
console.log("Connected successfully to server");
const db = client.db(dbName);
insertDocuments(db, function() { <------------------------ #99.2
client.close();
});
});
The best option is usually to consult the documentation.
The MongoClient.connect() doc (both #1 and #4) takes a callback function of type Callback<MongoClient>:
connect(callback: Callback<MongoClient>): void
And the Callback documentation is:
Callback<T>: (error?: AnyError, result?: T) => void
Defined in src/utils.ts:36
Type parameters
T = any
Type declaration
(error?: AnyError, result?: T): void
MongoDB Driver style callback
Parameters
Optional error: AnyError
Optional result: T
Returns void
Similarly toArray:
toArray(callback: Callback<TSchema[]>): void
and insertMany:
insertMany(docs: OptionalId<TSchema>[], options: BulkWriteOptions, callback: Callback<InsertManyResult<TSchema>>): void
For 99.1 the insertDocuments function was written to pass the result via callback
99.2 called insertDocuments, but apparently didn't care whether it succeeded or not, so it chose to ignore the result.

Looping through an array with PostgreSQL requests

I am attempting to store the contents of an array in my database. I want to add a new row for each item in the array. Currently I am running:
router.post('/saveVenueMatches', (req, res) => {
const id = req.body.user_id;
const data = req.body.data;
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');
for (const venue of data) {
let sqlText = `INSERT INTO user_matches (user_id, venue_id) VALUES ($1, $2)`;
pool
.query(sqlText, [id, venue.id])
.then((response) => {
res.send(response.rows);
})
.catch((err) => {
console.log('Error saving venue matches', err);
});
}
});
This results in successful posts to my database, however my server returns the following error once for each item in the array:
Error saving venue matches Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
{
code: 'ERR_HTTP_HEADERS_SENT'
}
I have tried removing the line where I set the header but I still get the error. I am not exactly sure what is causing this.
Additionally if there is a better way to make a request like this please let me know.
You're trying to send a result to client in each iteration of a cycle but you can do it only once. Try to send results after a cycle or better turn the cycle into Promise.all call
My suggestion will be to use multiple insert at once, dont try to hit database too many times.
You can use this npm packages for multiple insert at once
const pg = require('pg');
const format = require('pg-format');
you need to just format your data accordingly
let user_matches = [[1, 2], [2, 3]];
let query1 = format('INSERT INTO users (user_id, venue_id) VALUES %L returning id', user_matches);
let {rows} = await client.query(query);
for reference you can visit this website, please
click here

How do I reference my MongoDB data in NodeJS, and then add it to a Discord.JS message?

I'm trying to pull an array of data from a MongoDB database, and while the code is rusty (and I do want some corrections on it if it could be done better or is missing something or is wrong), it should be taking the array, finding the "user" and "description" objects, and then putting them into a discord.js message.
I've tried referencing the objects individually, making them strings, parsing the data, but I still cant find out how to do it. Heres the code I've been using.
module.exports.run = async (bot, message, args) => {
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb+srv://something:something#something/test?retryWrites=true&w=majority';
const assert = require('assert');
try {
function remindersChecker() {
let mongoClientPromise = MongoClient.connect(url, function (err, client) {
const db = client.db("reminders");
let date = new Date().getTime();
let now = Math.floor(Date.now() / 1000);
db.collection("reminders").find().toArray(function (err, result) {
let data = JSON.toObject();
console.log(data);
let user = data.author
let description = data.description
console.log(user);
user.send("I have a reminder for you! " + description)
})
})
}
remindersChecker()
} catch(err) {
catchError()
}
}}
module.exports.help = {
name: "check"
}
(The command is temporary and will be used on a setTimeout later, hence the function rather than just plain old code.)
Thanks! And I hope I can get help soon.
probably some more information would be great to better understand the problem.
from what i can see here, you are receiving an object from your database and converting it into an array here:
db.collection("reminders").find().toArray(function (err, result) {...
now that array is actually that result obtained from the callback and you are not using it at all, you probably have to iterate on that.
plus i remember that I used to write
...find({})..
to search in the database as for SELECT*FROM in SQL. maybe that can help too.
hope this helps.

Unable to deploy firebase function

Node.js command prompt is simply ignoring this function, while the other functions are getting deployed, I am not getting any error either.
var database = admin.database();
var postsRef = database.ref("/posts");
postsRef.on('child_added', addOrUpdateIndexRecord);
function addOrUpdateIndexRecord(dataSnapshot) {
// Get Firebase object
var firebaseObject = dataSnapshot.val();
// Specify Algolia's objectID using the Firebase object key
firebaseObject.objectID = dataSnapshot.key;
// Add or update object
index.saveObject(firebaseObject, function(err, content) {
if (err) {
throw err;
}
console.log('Firebase object indexed in Algolia', firebaseObject.objectID);
});
}
If it's a database trigger function, then the syntax you are using is not correct. Try doing this way:
exports.updateposts = functions.database.ref("posts/")
.onWrite(event => {
//Do whatever you want to do with trigger
});

How to pass data to Mongodb using Node.js, websocket and total.js

I am trying to pass data to Mongodb using Websocket and total.js.
In my homepage.html I can get the user input and connect to the server via websocket after clicking the save button.
In default.js is my server side code. At this point the app hat got the user input and connected to the server correctly, but how can I save data to mongodb now?
This is my homepage.html
<br />
<div>
<input type="text" name="message" placeholder="Service" maxlength="200" style="width:500px" />
<button name="send" >Save</div>
</div>
<br />
<script type="text/javascript">
var socket = null;
$(document).ready(function() {
connect();
$('button').bind('click', function() {
if (this.name === 'send') {
console.log(send());
return;
}
});
});
function connect() {
if (socket !== null)
return;
socket = new WebSocket('ws://127.0.0.1:8000/');
socket.onopen = function() {
console.log('open');
};
socket.onmessage = function(e) {
var el = $('#output');
var m = JSON.parse(decodeURIComponent(e.data)).message;
el.val(m + '\n' + el.val());
};
socket.onclose = function(e) {
// e.reason ==> total.js client.close('reason message');
console.log('close');
};
}
function send() {
var el = $('input[name="message"]');
var msg = el.val();
if (socket !== null && msg.length > 0)
socket.send(encodeURIComponent(JSON.stringify({ message: msg })));
el.val('');
return msg;
}
This is my default.js
exports.install = function(framework) {
framework.route('/', view_homepage);
framework.route('/usage/', view_usage);
framework.websocket('/', socket_homepage, ['json']);
};
function view_usage() {
var self = this;
self.plain(self.framework.usage(true));
}
function view_homepage() {
var self = this;
self.view('homepage');
}
function socket_homepage() {
var controller = this;
controller.on('open', function(client) {
console.log('Connect');
});
controller.on('message', function(client, message) {
console.log(message);
/*
var self = this;
var message = MODEL('message').schema;
var model = self.body;
var message = new message({ message: model.message }).save(function(err) {
if (err)
self.throw500(err);
// Read all messages
message.find(self.callback());
});
*/
});
controller.on('error', function(error, client) {
framework.error(error, 'websocket', controller.uri);
});
}
Any help Please!!!
This is complete project
---Update---
In this function i use to save data to MongoDB
but it didn't give any error.also Didnt save the data to database.i not sure my code is write or wrong
controller.on('message', function(client, message) {
console.log(message);
/*
var self = this;
var message = MODEL('message').schema;
var model = self.body;
var message = new message({ message: model.message }).save(function(err) {
if (err)
self.throw500(err);
// Read all messages
message.find(self.callback());
});
*/
});
This my mongoose.js
var mongoose = require('mongoose');
mongoose.connect('mongodb://totaldemo:123456#ds029979.mongolab.com:29979/totaldemo');
global.mongoose = mongoose;
This is my user.js
var userSchema = mongoose.Schema({ user: String})
exports.schema = mongoose.model('user', userSchema,'user');
exports.name = 'user';
I don't know totaljs framework at all, but i see some issues already with plain javascript.
First of all, i suggest You set up Your model like this:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema({
user: String
});
module.exports = mongoose.model('User', userSchema);
and then in controller, when You import:
var User = require('path/to/user/file')
You can use it like this straight away:
User.find()
Also - i totally dont get what are You doing later.
You defined user model and exported NOTHING MORE than a STRING. Only tthing it will do is, that when You import that user to variable User, the User.name will === to 'user' string. so in Your example it would be:
var User = require('path/to/user/model/file')
console.log(User.name) // prints 'user'
and nothing more! There are no models attached to that export. Maybe its how totaljs works, but i VERY doubt it.
Later on - You try to ... use message model. Where it comes from? You defined user model, not message model.
Another thing - as i stated - i dont know totaljs, but I doubt it ask YOu to define var model, and then never use variable model.
I strongly suggest using plain node with mongoose first, then try to integrate it with any fullstack.
For sure its not a solution, but maybe it points out some problems in Your code and will help.
EDIT:
I looked quickly in totaljs, and it looks that You really should export string (which is little weird and doing magic stuff:) ), but its NOT mongoose, and i guess will ONLY work with native totaljs model solution. You cant use mongoose and totaljs like that. I dont know how much not using native totaljs models system ruins framework other options, but its probably safer to use native one.
Honestly, i dont have time to look deeper into docs, but google says nothing about sql or even mongo inside of totaljs docs... so, You have to figure it out :)
EDIT2 i found https://github.com/totaljs/examples/tree/master/mongoose and it looks weird... check if that example works (looks like You seen it, Your code is similar :)). check if You're mongod is working, check if You can conenct from plain node...
Honestly sorry, i surrender. Totaljs has to much magic and abstraction for me to help You out with this :(. Hope You will find Your answer.

Categories