When creating new document in node js gives MongoError of write ECONNRESET.
Following is the error in console when creating the new document:
error: Error adding new agreementTemplate ! Error :
{"name":"MongoError","message":"write ECONNRESET"}
following is the controller function creating the error.
function addSubChapter(req, res) {
logger.debug('Processing request for creating a new agreement.');
console.log(req.body);
async.waterfall([
function (callback) {
agreementService.getAgreementTemplate( callback);
},
function (data, callback) {
agreementTmplService.AgreementTemplateSetDefaultFalse(function(err, result){
callback(null, data);
});
},
function (data, callback) {
var agreementTemplate =data.result[0];
var chapter ={
name: req.body.name
}
agreementTemplate = agreementTemplate.toObject(); // swap for a plain javascript object instance
delete agreementTemplate["_id"];
agreementTemplate.createdBy= req.body.user;
agreementTemplate.created= new Date();
//agreementTemplate.Chapters.push(chapter);
var chapters = agreementTemplate.Chapters;
for(var i=0;i<chapters.length; i++){
if(chapters[i].name == req.body.chapter){
var subChap ={
name: req.body.name
}
chapters[i].subChapters.push(subChap);
}
}
console.log('----------------------');
console.log(agreementTemplate);
agreementService.createAgreementTemplate(agreementTemplate, callback);
},
function (data, callback) {
agreementTmplService.addSubChapter(req.body, callback);
}
], function (err, result) {
utils.processResponse(err, result, res);
});
}
When creating the agreement template it causes the error, here is the service function:
function createAgreementTemplate(data, callback) {
serviceHelper.createModel(AgreementTemplate, 'agreementTemplate', data, callback);
}
and the createModel function is as follows.
function createModel(model, modelName, modelData, callback) {
logger.debug('Creating new Model : %s', modelName);
var modelObj = model(modelData);
modelObj.save(function (err, newModelObj) {
if (err) {
logger.error('Error adding new %s ! Error : %s', modelName, JSON.stringify(err));
callback(utils.handleMongodbError(err), null);
} else {
logger.info('New Model of type : %s created with id : %s', modelName, JSON.stringify(newModelObj._id));
var result = {};
result.status = httpStatus.OK;
result.result = newModelObj._id;
callback(null, result);
}
});
}
Related
I'm trying to use mongoose .select operator with my azure function but it keeps saying TypeError: db.collection(...).findOne(...).select is not a function at db.collection.find.toArray
It returns the user's data in the console, but doesn't filter it down with .select
Why is that?
var MongoClient = require('mongodb').MongoClient;
var Post = require('./model/post');
var mongoose = require('mongoose');
module.exports = async function (context, req) {
let currentPage = 1;
MongoClient.connect(process.env.CosmosDBConnectionString, async (err, client) => {
let send = response(client, context);
if (err) send(500, err.message);
let db = client.db(process.env.dbName);
await db.collection('listings').find(
{
$and: [
{ winnerHasBeenNotified: false },
{ auctionEndDateTime: { $lte: Date.now().toString() } }
]
}
)
.toArray((err, result) => {
console.log("result");
console.log(result);
if (result) {
for (let i = 0; i < result.length; i++) {
db.collection('users').findOne(
{
_id: mongoose.Types.ObjectId(result[i].bidderId)
}
).select("notificationBy").toArray((err, result) => {
console.log("USER RESULT!");
console.log(result);
});
}
}
if (err) send(500, err.message);
send(200, JSON.parse(JSON.stringify(result)));
});
});
};
function response(client, context) {
return function (status, body) {
context.res = {
status: status,
body: body
};
client.close();
context.done();
};
}
find() returns a cursor, which has a select method. findOne() retrieves a single document and returns a promise if no callback is provided.
If you are trying to get just the "notificationBy" field, try passing the fields option to findOne.
The callback function is not working as expected in a waterfall on async.for each limit.
When I remove that rest api call and if I call callback(null,arg2) it is working as expected, I think the problem with callback function or some api call in the below code.
var async = require("async");
var users = [1, 2, 3, 45]; // Initialize user array or get it from DB
var e = [];
var unirest = require("unirest");
var data = function() {
return new Promise((resolve, reject) => {
async.forEachLimit(
users,
1,
function(user, userCallback) {
async.waterfall(
[
function(callback) {
console.log(user);
callback(null, user);
},
function(arg1, callback) {
console.log(arg1);
callback(null, arg1);
},
function(arg2, callback) {
unirest
.get("http://dummy.restapiexample.com/api/v1/employee/1")
.end(function(response) {
if (response.error) callback("null", "data");
else callback(null, arg2);
});
}
],
function(err, result) {
if (err) {
console.log("err");
reject(e);
} else {
console.log("done", result);
e.push(result);
userCallback();
resolve(e);
}
}
);
},
function(err, result) {
console.log("User For Loop Completed", err, result);
}
);
});
};
I'm getting output as
expected outputs as
In the function below I'm retrieving an entity by id from a Mongo DB using Mongoose.
var Recipe = require('models/recipe').model;
exports.findById = function(req, res) {
Recipe.findById(req.params.id, function(err, docs) {
if (err) {
console.error(err);
res.status(500).send(err);
}
res.json(docs);
});
}
I would like to use Jasmine to test if I return a 500 when an error has been raised and I want to test if I put the JSON entity on the reponse when everything was successful.
I solved it by creating a closure containing the callback function, the advantage is that it's also reusable:
exports.jsonCallback = function(res) {
return function(err, docs) {
if (err) {
console.error(err);
res.status(500).send(err);
}
res.json(docs);
}
};
This allowed me to mock the response in a Jasmine test for the closure:
var resMock = {
status : function(status) {
return {
send : function() {}
}
},
json : function(json) {}
};
var mongooseCallback = require('controllers/callbacks/mongooseCallback').jsonCallback(resMock);
describe("when a json callback has been called", function() {
it("should return status 500 when an error has been raised", function() {
var returnStatusMock = { send : function() {}};
var errorMessage = "errorMessage";
spyOn(resMock, 'status').and.returnValue(returnStatusMock);
spyOn(returnStatusMock, 'send');
mongooseCallback(errorMessage, null);
expect(resMock.status).toHaveBeenCalledWith(500);
expect(returnStatusMock.send).toHaveBeenCalledWith(errorMessage);
});
it("should return the corresponding document in a json format", function() {
spyOn(resMock, 'json');
var jsonString = "{ 'name' : 'value' }";
mongooseCallback(null, jsonString);
expect(resMock.json).toHaveBeenCalledWith(jsonString);
});
});
Hi I have this code but when finish the result is not the espected because didn't run in the sequence that I wish
here is the code:
var user_data = {};
models.games.find({$or: [{w_id: req.user._id}, {b_id: req.user._id}, {owner: req.user._id}]}, function (err, games) {
var req_games = [];
if (!err) {
for (var i in games) {
req_games.push(games[i]);
models.users.findOne({_id: games[i].w_id}, function (err, user) {
req_games[i].w_id = user.user;
console.log(req_games[i].w_id) //< -- 3
});
console.log('a ' + req_games[i].w_id) //<-- 2
}
user_data.games = req_games; // <-- 1
}
});
at the end of the task req_games didnt have any update because it's running in the sequence that I put in the comments in the code
This may help you using Q(promises)
obj.find = function(model, condition) { //make your find to return promise
var deferred = q.defer();
model.find(condition, function(err, results) {
if (err) {
logger.log(err);
deferred.reject(err);
} else {
deferred.resolve(results);
}
});
return deferred.promise;
}
ArraysOfId.forEach(function (id) {
var tempProm = mongoUtilsMethodObj.find(schemaObj.Asset, id).then(function (assetObj) {
---- your code
return q.resolve();
});
promArr.push(tempProm);//push all promise to array
});
q.all(promArr).then(function () {
// this will be called when all promise in array will we resolved
})
Here is a version using the async library to map your game values.
var async = require('async');
var user_data = {};
models.games.find({$or: [{w_id: req.user._id}, {b_id: req.user._id}, {owner: req.user._id}]}, function (err, games) {
if(err) {
// or whatever your error response happens to be
return res.render('user.swig', {error: err});
}
async.map(games, function(game, nextGame) {
models.users.findOne({_id: game.w_id}, function (err, user) {
game.w_id = user.user;
nextGame(err, game);
});
}, function(err, req_games) {
user_data.games = req_games;
res.render('user.swig', {user: user_data});
});
});
When I run collection.find() in MongoDB/Node/Express, I need to return value for my array like this but iam in callback hell;
foursquare.getVenues(params,function(error, venues) {
if (!error) {
var places = [];
venues.response.venues.forEach(function(e) {
places.push(
{
obj_id:e.id,
name:e.name,
distance:e.distance,
here_now:req.collection.findById(e.id) //count- i want need this value
}
);
});
res.send(places);
}
});
You can try to use Async https://github.com/caolan/async#each
var async = require('async');
...
foursquare.getVenues(params, function (error, venues) {
if (!error) {
throw err;
}
var places = [];
async.each(venues.response.venues, function (e, callback) {
db.collection.findById(e.id, function (err, res) {
places.push({
obj_id: e.id,
name: e.name,
distance: e.distance,
here_now: res
});
callback()
});
}, function (err) {
if (err) {
console.log('A file failed to process');
} else {
console.log('All files have been processed successfully');
res.send(places);
}
});
});
or Using async.map
var async = require('async');
var createArray = function (e, cb) {
db.collection.findById(e.id,function(err,res){
var obj = {
obj_id: e.id,
name: e.name,
distance: e.distance,
here_now: res
}
cb(null, obj);
});
}
async.map(venues.response.venues, createArray, function (err, places) {
if(err){
throw err;
}
console.log(places);
});