I working with CarboneJS in NodeJS, in order to generate reports.
This is the documentation : https://carbone.io/documentation.html#getting-started-with-carbone-js
To use CarboneJS is simple:
carbone.render('./node_modules/carbone/examples/simple.odt', data, function(err, result){
if (err) {
return console.log(err);
}
fs.writeFileSync('result.odt', result);
});
What I want to do, is pass my own template (Which it stored in database), lets call it for example MyFileFromDatabase so I can do something like this :
const MyFileFromDatabase = new Buffer (myFile);
carbone.render(MyFileFromDatabase, data, function(err, result){
if (err) {
return console.log(err);
}
// write the result
fs.writeFileSync('result.odt', result);
});
What Im expecting to get : Carbone will render the document.
What I get :
complete erreur sendErrorHttp: TypeError: Cannot read property 'length' of undefined
I don"t know if such feature exist, or should I go with other strategies? Like using Streams?
For now, it is not possible to pass a buffer to the render function.
However, it is already a feature request and the team will probably work on it really soon. Here is the issue on Github: https://github.com/carboneio/carbone/issues/119
A quick alternative is to use the Carbone Render API, which gives you the possibility to pass the template as a Buffer or as a base64 String. You got 100 render for free per month Here is the documentation https://carbone.io/api-reference.html#carbone-render-api
A node SDK is available to call the API easily.
I will update the thread when the buffer feature is out!
Related
Trying to make a file that render into ejs how can i do this
let makeFile = res.view('file.ejs',{result:result});
fs.writeFile(sails.config.myconf.path+'file.xml', makeFile, function (err, result) {
if(err){
console.log(err)
return
}
});
Tried this way getting undefined always can any one please understand why this is causing issue thanks a ton in advance
res.view is really meant to come at the end of your method. It facilitates a return sent by the res object, and I don't think it returns anything useful.
What you want is likely res.render - you can use that to get (and then work with) the output html as a string.
res.render('file.ejs', {result: result}, function(err, renderedHtml) {
if (err) { /* handle the error */ }
// renderedHtml should be the html output from your template
// use it to write a new file, or whatever is required
console.log(renderedHtml);
return res.send({fileCreated: true});
});
I am using Model.create(Array) in Mongoose.
I want to provide user a feedback about how many documents have been created and how many of them haven't (i.e. they didn't validate).
I created a callback like this
User.create(usersToImport, function(err, docs) {
console.log(err);
console.log(docs);
}
The problem is that if any document does not validate, I only receive a validation error on the single non-valid document, while I cannot retrieve any information about the inserted documents.
Is there any way to get this information?
I think, you need something like .settle() method from when.js module.
Here is an example of doing it using when.js with mongoose 3.8.x:
when = require('when');
promises = usersToImport.map(function(user) {
return User.create(user); // returns Promise
});
when.settle(promises).then(function(results) {
// results is an array, containing following elements:
// { state: 'fulfilled', value: <document> }
// { state: 'rejected', value: <error> }
});
It's possible to do it without Promises (e.g. using async module), but the code will be much more complicated.
Model.create() isn't going to return that information for you. The best option would be to roll your own version of Model.create(), which is essentially a convenience method for calling Model.save() multiple times, and collate the information yourself. A good way to get started is the code for Model.create().
Hi im developing an app with nodeJS, express and a mongoDB, i need to take users data from a csv file and upload it to my database this db has a schema designed with mongoose.
but i don know how to do this, what is the best approach to read the csv file check for duplicates against the db and if the user (one column in the csv) is not here insert it?
are there some module to do this? or i need to build it from scratch? im pretty new to nodeJS
i need a few advices here
Thanks
this app have an angular frontend so the user can upload the file, maybe i should read the csv in the front end and transform it into an array for node, then insert it?
Use one of the several node.js csv libraries like this one, and then you can probably just run an upsert on the user name.
An upsert is an update query with the upsert flag set to true: {upsert: true}. This will insert a new record only if the search returns zero results. So you query may look something like this:
db.collection.update({username: userName}, newDocumentObj, {upsert: true})
Where userName is the current username you're working with and newDocumentObj is the json document that may need to be inserted.
However, if the query does return a result, it performs an update on those records.
EDIT:
I've decided that an upsert is not appropriate for this but I'm going to leave the description.
You're probably going to need to do two queries here, a find and a conditional insert. For this find query I'd use the toArray() function (instead of a stream) since you are expecting 0 or 1 results. Check if you got a result on the username and if not insert the data.
Read about node's mongodb library here.
EDIT in response to your comment:
It looks like you're reading data from a local csv file, so you should be able to structure you program like:
function connect(callback) {
connStr = 'mongodb://' + host + ':' + port + '/' + schema; //command line args, may or may not be needed, hard code if not I guess
MongoClient.connect(connStr, function(err, db) {
if(err) {
callback(err, null);
} else {
colObj = db.collection(collection); //command line arg, hard code if not needed
callback(null, colObj);
}
});
}
connect(function(err, colObj) {
if(err) {
console.log('Error:', err.stack);
process.exit(0);
} else {
console.log('Connected');
doWork(colObj, function(err) {
if(err) {
console.log(err.stack);
process.exit(0);
}
});
}
});
function doWork(colObj, callback) {
csv().from('/path/to/file.csv').on('data', function(data) {
//mongo query(colObj.find) for data.username or however the data is structured
//inside callback for colObj.find, check for results, if no results insert data with colObj.insert, callback for doWork inside callback for insert or else of find query check
});
}
I have the following problem with mongodb-native. I have a function whose purpose is to return some element from db.
function get(){
db.collection('test').findOne({...},{...},function(err, doc){
// my doc is here
});
// but here my doc is undefined
// so I can not return it
return doc;
}
So due to asynchroneous nature of node, I can not get my doc back. So how can I make it synchroneous (or is there any other way)?
I need for my single page app. So when my client does some action, ajax request is sent which is handled by get function. This function has to send back JSON.
The answer is to have your code work asynchroneous, that is the whole concept of JavaScript.
Thus if you have something like this in your synchroneous program:
function get() {
db.collection('test').findOne({...},{...},function(err,doc) {
});
return doc;
}
var doc = get();
console.log(doc);
You can refactor it into:
function printToConsole(err, doc) {
console.log(doc);
}
function get(callback) {
db.collection('test').findOne({...},{...},callback);
}
get(printToConsole);
It is not a unique solution, there are other workflows. Some like promises will make your code flatter.
But my personal suggestion, is to initially learn how to code asynchroneous code without supporting libraries. Initially it feels like a pain, just give it some time and you will start enjoying the idea.
I think this is a very simple question? I am a beginner trying to learn mongo with node.
Once I have saved something to a collection, how can I pull it out in simple var format?
db.highschools.save({
hsid :10,
name :"Johnson High School",
location:"San Diego, CA"
});
I simply want to store a var as 'Johnson High School'.
My failed attempts that have returned undefined are as follows...
var hsName = db.highschools.find({hsid:10}).name;
var hsName = db.highschools.find({hsid:10}).name.str;
Pretty sure I'm missing the big picture here, would someone please be kind enough to help me figure this out?
Use findOne instead:
var hsName = db.highschools.findOne({hsid:10}).name;
Also, note that this is a Mongo script, not a NodeJS script.
You'll need to make it async when you write the logic in NodeJS.
db.collection('students', function(err, collection) {
collection.findOne({hsid:10}, function(err, student) {
if (err) { throw err; }
console.log(student.name);
});
});
If you're confident that there should be only one result, then you can use the shortcut method findOne which simply calls find internally with a limit of one. If you were to use find, it returns an array of matches.