Use find on a model inside a static - node.js

What I try to do is something like this:
A_Schema.statics.init = function init() {
A_Schema.find({}, {}, {
}, function (error, docs) {
if (!error) {
console.log('There is no error.');
}
else {
console.log(error);
}
});
};
I mean, using the find method of the A_Schema model but it keeps crashing.
I suppose that is because the inner A_Schema is must be a properly defined Model and not a Schema, but I don't know how to do it.
I already tried:
A_Schema.statics.init = function init() {
mongoose.model('A_Schema', A_Schema).find({}, {}, {
}, function (error, docs) {
if (!error) {
console.log('There is no error.');
}
else {
console.log(error);
}
});
};
and
A_Schema.statics.init = function init() {
mongoose.model('A_Schema').find({}, {}, {
}, function (error, docs) {
if (!error) {
console.log('There is no error.');
}
else {
console.log(error);
}
});
};
but it keep crashing.
Can you help me?
Thanks in advance
Diosney

Sorry, it seems that I overlook the mongoose documentation.
At mongoose documentation can be see the example:
animalSchema.statics.findByName = function (name, cb) {
this.find({ name: new RegExp(name, 'i') }, cb);
}
So, inside a static the this reference must be used instead of the named model.

Related

How do I run a function after using array.map?

What I'm trying to do is run a function after using array.map. Theoretically, I should be able to just run the after the array.map. However, for some reason, it's running the function before array.map is finished. How do I fix this?
Here's my code.
var channelIds = channelNames.map(function (name) {
request(`https://www.googleapis.com/youtube/v3/channels?key=${key}&forUsername=${name}&part=id`, function (error, response, body) {
if (error) {
callback(error);
} else {
var data = JSON.parse(body);
if (data.items.length == 0) {
callback(`Error: No channel id found for ${name}`);
} else {
return data.items[0].id;
}
}
});
});
function test() {
console.log(channelIds);
}
test();
EDIT:
One way which was suggested was to use async.map. For some reason, it doesn't want to run the specified callback function like how the documentation says it should.
Here's how I'm doing it now.
async.map(channelNames, function (name) {
request(`https://www.googleapis.com/youtube/v3/channels?key=${key}&forUsername=${name}&part=id`, function (error, response, body) {
if (error) {
callback(error);
} else {
var data = JSON.parse(body);
if (data.items.length == 0) {
callback(`Error: No channel id found for ${name}`);
} else {
return data.items[0].id;
}
}
});
}, function (error, results) {
console.log(results);
});
Documentation: https://caolan.github.io/async/docs.html#map
How about using Promise.all to resolve all async functions before you call test method?
Try this :
const promiseArray = channelNames.map(function (name) {
return new Promise(function (resolve, reject) {
request(`https://www.googleapis.com/youtube/v3/channels?key=${key}&forUsername=${name}&part=id`, function (error, response, body) {
if (error) {
callback(error); return reject(error);
} else {
var data = JSON.parse(body);
if (data.items.length == 0) {
callback(`Error: No channel id found for ${name}`);
return reject(`Error: No channel id found for ${name}`);
} else {
return resolve(data.items[0].id);
}
}
});
});
});
Promise.all(promiseArray).then(function(channelIds) {
console.log(channelIds);
})

async function is not working in node js

I am trying to develop an APP in which I have to increase or decrease the user count according to their hobbies/interest in the master list. I am doing it in Node js with the help of loopback. Here is my code, in which I am giving two interests(i.e sketching and horse-riding):
async.forEach(data, function (interest) {
console.log("Interest is", interest);
Interest.findOne({
where:
{
'name': interest
}
}, function (err, interestObj) {
if (err) {
//return callback(err, null);
console.log("error", err);
}
else {
//return callback(null, response);
console.log("found", interestObj);
if (!interestObj) {
Interest.create({ "name": interest, "count": 1 }, function (err, response) { });
}
else {
_count = interestObj.count + 1;
interestObj.updateAttribute('count', _count, function (e, r) { });
}
}
});
// return callback(null, {});
},function(err){
console.log("success..!!")
});
}
but it is showing me only one of them in output. Here is output:
data is [ 'horse-riding', 'skeching' ]
Interest is horse-riding
Interest is skeching
found { name: 'horse-riding', count: 1, id: 59ccff0765055a212491a6bc }
found null
I think the async function is not working properly with forEach loop in this, But I am not getting where the code went wrong. I want to show all the interest given by the user, so what course of actions should I take to do it?? Thanks in advance..!!:)
It is working now...!!!
async.each(data, function (interest, callback2) {
console.log('Processing ', interest);
Interest.findOne({
where:
{
'name': interest
}
}, function (err, interestObj) {
if (err) {
console.log("error", err);
callback2(err);
}
else {
console.log("found", interestObj);
if (!interestObj) {
Interest.create({ "name": interest, "count": 1 }, function (err, response) { });
}
else {
_count = interestObj.count + 1;
interestObj.updateAttribute('count', _count, function (e, r) { });
}
callback2();
}
});
}, function (err) {
if (err) {
console.log('Failed to process', err);
} else {
console.log('All interests have been processed successfully');
}
return callback(err);
})
};

Insert array of objects in only one document

i'm trying to insert a new document in my Mongo database like this:
MongoClient.connect(MongoURL, function(error, database) {
var collection;
if (error) {
console.log(error);
}
collection = database.collection(job);
collection.insert(json, function(error, result) {
if (error) {
return console.log(error);
} else {
return console.log(result);
}
});
});
And is working, but not like i want.
The 'json' is an array of objects, like this:
json = [
{
"name": "Paulo"
},
{
"name": "José"
}
....
]
So, my code is creating one document for object, and i want create just one document with the objects inside a property called json:
{
json: [
{...},
{...},
{...}
]
}
Is this possible?
I tried to use insertMany, also.
Thanks.
Please try this one,
var obj = {};
obj.json = json;
col.insert(obj, function(error, result) {
if (error) {
return console.log(error);
} else {
return console.log(result);
}
});

async.parallel inside async.series

I have this async.parallel functionality inside an aysnc.eachSeries call.
I hardcoded an error so I could pass it, to see if it was behaving the way I thought. For some reason, when I pass an error, it doesn't get thrown in the final callback named "doneWithSeries".
async.eachSeries(jsonDataArr, function iterator(item, callback) {
async.parallel([
function (cb) {
if (item.hasOwnProperty('event.type')) {
var event_type = item['event.type'];
delete item['event.type'];
try {
var json = JSON.stringify(item);
}
catch (err) {
throw err;
}
fs.writeFile('./enriched_data/' + event_type + '.json', json, function (err) {
if (err) {
cb(err);
}
else {
cb(null);
}
});
}
},
function (cb) {
if (item.hasOwnProperty('status_desc')) {
var status_desc = item['status_desc'];
delete item['status_desc'];
try {
var json = JSON.stringify(item);
}
catch (err) {
throw err;
}
fs.writeFile('./enriched_data/' + status_desc + '.json', json, function (err) {
if (err) {
cb(err);
}
else {
cb(null);
}
});
}
}
],
function doneWithParallel(err) {
callback(new Error('throw this baby')); //shouldn't the first incident of error pass the error straight to the doneWithSeries callback below?
})
},
function doneWithSeries(err) {
if (err) {
throw err;
}
else {
console.log('success');
}
});
here is a distilled version of the code without anything unnecessary:
var async = require('async');
async.eachSeries(['1', '2'], function (item, callback) {
async.parallel([
function (cb) {
setTimeout(function () {
cb(null, 'one');
}, 200);
},
function (cb) {
setTimeout(function () {
cb(null, 'two');
}, 100);
}
],
function doneWithParallel(err, results) {
console.log('results', results);
callback(new Error('duh'));
})
},
function doneWithSeries(err) {
if (err)
throw err;
});
indeed that works. can't figure out why my code above doesn't, accept perhaps that the array could be empty even though when I run my code the success message gets logged...weird.
I think that's expected behavior if your list is empty. async will always call the final callback with no error even if there is no input list.

No duplicate one try/catch by waterfall function (using async waterfall)

I'm using async waterfall and i've got a question about try/catch error.
I wan't to dodge this syntax method with one global try/catch and no duplicate a try/catch by function :
async.waterfall([
function (callback) {
try {
this.foo() // Ok
this.bar() // Method bar doesn't exist so without try/catch node will crash
} catch(ex) {
//print err
}
},
function (callback) {
try {
//Again & again
} catch(ex) {
//print err
}
}
//... function() with try catch ...
], function(err, result) {
//Do something
})
If you seek a more robust error handling system; try this:
var async = require('async');
function callbackErrorHandler(fn, callback) {
try {
fn()
} catch (err) {
callback(err);
}
}
async.waterfall([
function(callback) {
callbackErrorHandler(function() {
throw new Error('error1');
}, callback);
},
function(callback) {
callbackErrorHandler(function() {
throw new Error('error2');
}, callback);
}
],
//final
function(err, result) {
console.log(err);
});
/**
* Using Promises
*/
var async = require('async');
//promises
var Promises = require('bluebird');
function callbackErrorHandler(fn) {
return new Promises(function(resolve, reject) {
try {
resolve(fn()); //should return something
} catch (err) {
reject(err);
}
});
}
async.waterfall([
function(callback) {
callbackErrorHandler(function() {
throw new Error('error1');
})
.error(callback)
},
function(callback) {
callbackErrorHandler(function() {
throw new Error('error2');
})
.error(callback)
}
],
//final
function(err, result) {
console.log(err);
});
This script no longer print in final callback and crash node server :
Test this and try to rename test() by testt()
'use strict'
var async = require('./lib/node_modules/async')
function test()
{
console.log("hi !")
}
async.waterfall([
function(callback){
callback(null)
},
function(callback){
test()
callback(null, null)
}], function (err, result) {
if (err)
{
console.log("got an error !")
}
else
{
console.log("everyting is ok")
}
}
)

Resources