TypeError: pipeline[(pipeline.length - 1)] is undefined - mongodb

I am running mongodb queries dynamically I am getting this error :
TypeError: pipeline[(pipeline.length - 1)] is undefined :
The following is my query :
var a = { "aggregate" : "income", "pipeline" : [ {$match:{sal : {$gt : 10000}}},{ "$skip" : 0}, { "$limit" : 5000 }], "cursor" : { "batchSize" : 5000 } };
if(a["aggregate"] != undefined)
{
var collectionName = a["aggregate"];
var query = a["pipeline"];
print(query)
for(var k = 0;k<query.length;k++)
{
var b = query[k]
if(b["$skip"] != undefined)
{
delete query[k];
}
if(b["$limit"] != undefined)
{
delete query[k];
}
}
print(query)
db.getCollection(collectionName).aggregate(query)
}
Please help
Regards
Kris

Hope this answer may help someone:
var a = { "aggregate" : "income", "pipeline" : [ {$match:{sal : {$gt : 10000}}},{ "$skip" : 0}, { "$limit" : 5000 }], "cursor" : { "batchSize" : 5000 } };
if(a["aggregate"] != undefined)
{
var collectionName = a["aggregate"];
var foo = [];
var query = a["pipeline"];
print(query)
for(var k = 0;k<query.length;k++)
{
var b = query[k]
if(b["$skip"] != undefined)
{
delete query[k];
}
else if(b["$limit"] != undefined)
{
delete query[k];
}
else
{
foo.push( query[k]);
}
}
db.getCollection(collectionName).aggregate(foo)
}

Related

updateOne command in mongoose 5.5.11 every time I execute, I get response { "n": 0, "nModified": 0, "ok": 1 } ! what's going wrong?

I 'm trying to update a MongoDB document by mongoose model.updateOne command, But every time I execute the command, it responds {ok:1, n:0, nModified:0}
Mongoose model :
var mongoose = require('mongoose');
var measurepropsSchema = new mongoose.Schema({
measureTitle: {
type: String,
unique: true,
required: true
},
measureDescription: {
type:String,
required:false
},
measureSymbol: {
type: String,
required:false,
}
});
var collectionName = 'measureParams'
mongoose.model('Mp', measurepropsSchema, collectionName);
router :
routerm.put('/editbyid/:id', ctrlMeasProps.edit);
Route configuration :
var routesMea = require('./api/routes/measures');
app.use('/mea', routesMea);
and finally edit function :
var Mp = mongoose.model('Mp');
module.exports.edit = function (req, res) {
var measureParams = new Mp();
console.log(req.body);
try{
measureParams.updateOne(
{ _id: req.params.id },
{
measureTitle: req.body.title,
measureDescription: req.body.description,
measureSymbol: req.body.symbol
},
(err, docu) => {
console.log(measureParams);
console.log(err);
console.log('fin');
if (err)
return res.status(500).send(err);
return res.send(docu);
}
)
}catch(e){
console.log(e);
}
};
I requested the below link,
http://localhost:3000/mea/editbyid/5ce8e8555647bf5fb1b51803
requested body is a JSON object like this :
{
"title": "sth",
"description": "It`s sth",
"symbol": "$0"
}
and it responds :
{
"n": 0,
"nModified": 0,
"ok": 1
}
Here is collection "measureParams" data:
{ "_id" : ObjectId("5ce8e8375647bf5fb1b51802"), "measureTitle" : "AAAA", "measureDescription" : "It`s AAAA", "measureSymbol" : "%$" }
{ "_id" : ObjectId("5ce8e8555647bf5fb1b51803"), "measureTitle" : "BBBB", "measureDescription" : "It`s BBBB", "measureSymbol" : "##" }
{ "_id" : ObjectId("5ce8f3b96bcf65fade7c5bcf"), "measureTitle" : "CCCC", "measureDescription" : "It`s CCCC", "measureSymbol" : "$$" }
{ "_id" : ObjectId("5ce90bb3b78b6fbd4b9781ed"), "measureTitle" : "DDDD", "measureDescription" : "It`s DDDD", "measureSymbol" : "#$" }
{ "_id" : ObjectId("5ce90ed9de934a056c00a383"), "measureSymbol" : "Or", "measureDescription" : "It`s EEEE", "measureTitle" : "EEEE", "__v" : 0 }
{ "_id" : ObjectId("5ce912bc5a52000e009b6f2e"), "measureSymbol" : "Ol", "measureDescription" : "It`s FFFF", "measureTitle" : "FFFF", "__v" : 0 }
{ "_id" : ObjectId("5ce937907d656012902702cb"), "measureTitle" : "GGGG", "measureDescription" : "It`s GGGG", "measureSymbol" : "QS", "__v" : 0 }
It should update collection by ObjectId 5ce8e8555647bf5fb1b51803 with new values mentioned in json body, but it does't.
I don't know what is the problem?
Do you have any idea?
updateOne works with model name , try to update your edit function and schema file :
update last line in schema file to this :
var Mp = module.exports = mongoose.model('Mp', measurepropsSchema, collectionName);
And Edit function should look like this:
var Mp = require('/path/to/Mp/schema/file');
module.exports.edit = function (req, res) {
console.log(req.body);
try{
Mp.updateOne(
{ _id: req.params.id },
{
measureTitle: req.body.title,
measureDescription: req.body.description,
measureSymbol: req.body.symbol
},
(err, docu) => {
console.log(err);
console.log('fin');
if (err)
return res.status(500).send(err);
return res.send(docu);
}
)
}catch(e){
console.log(e);
}
};

How to get document field in variable for mongodb

How to get document field in variable for mongodb
This code is not work:
db.Conversation.find().forEach(function(item)
{
var _message = db.Message.find({ ConversationId : item._id.toString(), IsAgent : true }).sort({ SendDate: 1 }).limit(1);
if(_message._id != null)
{
item.FirstAgentMessageId = _message._id.toString();
item.FirstAgentMessageDate = _message.SendDate;
db.Conversation.save(item);
}
})
Thanx
Successful code:
db.Conversation.find().forEach(function(item)
{
var _message = db.Message.find({ ConversationId : item._id.str, IsAgent : true }).sort({ SendDate: 1 }).limit(1).toArray()[0]
if(isObject(_message))
{
item.FirstAgentMessageId = _message._id.str
item.FirstAgentMessageDate = _message.SendDate;
db.Conversation.save(item);
}
})

Creating Mongo/mapReduce data source in icCube

I would like to create a MongoDB/mapReduce data source into icCube (http://www.iccube.com/support/documentation/user_guide/schemas_cubes/ds_mongodb.php#mapReduce), The below script works fine from Mongo shell, how it should be formatted to be accepted by icCube, when I paste the same code into icCube datasource builder, I get this error message:
MongoDB : invalid JSON (table:Test.mapReduce) : [var location_map = function() { if (this.companyId = "1234" && this.Parent_Location !== undefined && this.Parent_Location.value.length > 0 && this.Parent_Location.value[0].id !== undefined && this.Parent_Location.value[0].id !== null) { emit(this.Parent_Location.value[0].id, {Location_NameOfLocation: this.Location_NameOfLocation, LocationID: this._id, CountryName: "", companyId : 0}); } } var country_map = function() { if (this.companyId = "1234") { emit(this._id, { CountryName: this.CountryName, Location_NameOfLocation: "", LocationID: 0, companyId : this.companyId }); } } var r = function(key, values) { var result = {LocationID: 0, CountryName: "", Location_NameOfLocation: "", companyId : 0}; values.forEach(function(value) { if (result.LocationID === 0 && value.LocationID !== null ) { result.LocationID = value.LocationID; } if (result.companyId === 0 && value.companyId !== null ) { result.companyId = value.companyId; } if (result.CountryName === "" && value.CountryName !== null ) { result.CountryName = value.CountryName; } if (result.Location_NameOfLocation === "" && value.Location_NameOfLocation !== null ) { result.Location_NameOfLocation = value.Location_NameOfLocation; } }); return result; } db.runCommand( { mapReduce: Location, map: location_map, reduce: r, out: { replace: LocationsCountries }, query: {companyId : "1234"} } ) db.runCommand( { mapReduce: Countries, map: country_map, reduce: r, out: { reduce: LocationsCountries }, query: {companyId : "1234" } } )] ^
Mongo mapReduce script:
var location_map = function() {
if (this.companyId = "1234" && this.Parent_Location !== undefined && this.Parent_Location.value.length > 0 && this.Parent_Location.value[0].id !== undefined && this.Parent_Location.value[0].id !== null) {
emit(this.Parent_Location.value[0].id, {Location_NameOfLocation: this.Location_NameOfLocation, LocationID: this._id, CountryName: "", companyId : 0});
}
}
var country_map = function() {
if (this.companyId = "1234") {
emit(this._id, { CountryName: this.CountryName, Location_NameOfLocation: "", LocationID: 0, companyId : this.companyId });
}
}
var r = function(key, values) {
var result = {LocationID: 0, CountryName: "", Location_NameOfLocation: "", companyId : 0};
values.forEach(function(value) {
if (result.LocationID === 0 && value.LocationID !== null ) { result.LocationID = value.LocationID; }
if (result.companyId === 0 && value.companyId !== null ) { result.companyId = value.companyId; }
if (result.CountryName === "" && value.CountryName !== null ) { result.CountryName = value.CountryName; }
if (result.Location_NameOfLocation === "" && value.Location_NameOfLocation !== null ) { result.Location_NameOfLocation = value.Location_NameOfLocation; }
});
return result;
}
db.runCommand(
{
mapReduce: "Location",
map: location_map,
reduce: r,
out: { replace: "LocationsCountries" },
query: {companyId : "1234"}
}
)
db.runCommand(
{
mapReduce: "Countries",
map: country_map,
reduce: r,
out: { reduce: "LocationsCountries" },
query: {companyId : "1234" }
}
)
Thanks,
Balint
You'll have to define your functions in strings ( and Javascript escape if required strings within these strings ). This is described here in the icCube documentation ( www ). Here is an example combining single quoted strings with double-quoted strings.
{
"mapReduce": "Location",
"map": 'function() {
if (this.companyId = "1234" && this.Parent_Location !== undefined && this.Parent_Location.value.length > 0 && this.Parent_Location.value[0].id !== undefined && this.Parent_Location.value[0].id !== null) {
emit(this.Parent_Location.value[0].id, {Location_NameOfLocation: this.Location_NameOfLocation, LocationID: this._id, CountryName: "", companyId : 0});
}
}',
"reduce": 'function(key, values) {
var result = {LocationID: 0, CountryName: "", Location_NameOfLocation: "", companyId : 0};
values.forEach(function(value) {
if (result.LocationID === 0 && value.LocationID !== null ) { result.LocationID = value.LocationID; }
if (result.companyId === 0 && value.companyId !== null ) { result.companyId = value.companyId; }
if (result.CountryName === "" && value.CountryName !== null ) { result.CountryName = value.CountryName; }
if (result.Location_NameOfLocation === "" && value.Location_NameOfLocation !== null ) { result.Location_NameOfLocation = value.Location_NameOfLocation; }
});
return result;
}',
"out": {
"replace": "LocationsCountries"
},
"query": {
"companyId" : "1234"
}
}

jstree initially_select and initially_open

The below lines of code while using jstree, throws an exception mentioned in the link
http://code.google.com/p/jstree/issues/detail?id=294
**"ui" : { "initially_select" : [ quotedAndCommaSeparated ] }**
**"core" : { "animation" : 0, "initially_open" : [ quotedAndCommaSeparated ] }**
If i use hard coded values like below, it works without any issues.
"ui" : { "initially_select" : ['3381','7472','7473','7474','7247','7248','7249','3273','3272'] }
"core" : { "animation" : 0, "initially_open" : [ '3381','7472','7473','7474','7247','7248','7249','3273','3272' ] }
I have formed the quotedAndCommaSeparated from an array and it is the same as the hard coded values above. But still the issue is not resolved. Please suggest.
quotedAndCommaSeparated = '3381','7472','7473','7474','7247','7248','7249','3273','3272'
Complete code for ur reference:
For Scripts:
static.jstree.com/v.1.0pre/jquery.jstree.js
static.jstree.com/v.1.0pre/_docs/syntax/!script.js
function BindTreeView(nodeToHighlight, isInitialLoad)
{
var initiallySelect = [];
var searchOption = 0;
if($('#rbobtnSelectedLevelAndBelowRadio:checked').val() == 'Selected Level and Below')
searchOption = 1;
else if($('#rdobtnCurrentOrganization:checked').val() == 'Current Organization')
searchOption = 2;
if(searchOption == 0)
initiallySelect.push(nodeToHighlight);
else if (searchOption == 1 || searchOption == 2)
{
var grid = $("#SearchResultJQGrid");
ids = grid.jqGrid("getDataIDs");
if(ids && ids.length > 0)
{
for(var iRow = 1; iRow < ids.length; iRow++)
{
var dataRow = $("#SearchResultJQGrid").getRowData(iRow);
var companyId = dataRow.CompanyID;
initiallySelect.push(companyId);
}
}
}
var quotedAndCommaSeparated = "'" + initiallySelect.join("','") + "'";
var urlRef = '/Group/GetDataForTreeView';
$('#TreeView').jstree({
"json_data" : {
"ajax" : {
"cache": false,
"url": function (node) {
var nodeId = "";
if (node == -1)
url = urlRef;
return url;
},
"data" : function (n) {
return { id : n.attr ? n.attr("id") : 0 };
}
}
},
"ui" : { "initially_select" : [ quotedAndCommaSeparated ] },
"core" : { "animation" : 0, "initially_open" : [ quotedAndCommaSeparated ] },
"themes": {
"theme": "classic",
"dots": true,
"icons": false
},
"plugins" : [ "themes", "json_data", "ui", "core" ]
}).bind("select_node.jstree", function (event, data) { if(isInitialLoad == true)
isInitialLoad = false;
else
BindGridView('CV', data.rslt.obj.attr("name"), data.rslt.obj.attr("id"), isInitialLoad);
});
}
Your bug is that quotedAndCommaSeparated is not a list, it's just a string.
You should simply add strings instead of numbers to the initiallySelect list
initiallySelect.push(companyId + "");
Then you can use this directly in the jstree init
"ui" : { "initially_select" : [ initiallySelect ] },
Hope that helps.

How to calculate ratios for an additive attribute with mongodb?

Using the sample mongodb aggregation collection (http://media.mongodb.org/zips.json), I would like to output the population share of every city in California.
In SQL, it could look like this:
SELECT city, population/SUM(population) as poppct
FROM (
SELECT city, SUM(population) as population
FROM zipcodes
WHERE state='CA'
GROUP BY city
) agg group by state;
This can be done using mongodb map/reduce:
db.runCommand({
mapreduce : "zipcodes"
, out : { inline : 1}
, query : {state: "CA"}
, map : function() {
emit(this.city, this.pop);
cache.totalpop = cache.totalpop || 0;
cache.totalpop += this.pop;
}
, reduce : function(key, values) {
var pop = 0;
values.forEach(function(value) {
if (value && typeof value == 'number' && value > 0) pop += value;
});
return pop;
}
, finalize: function(key, reduced) {
return reduced/cache.totalpop;
}
, scope: { cache: { } }
});
Can this be also achieved using the new aggregation framework (v2.2)? This would require some form of global scope, as in the map/reduce case.
Thanks.
Is this what you're after?
db.zipcodes.remove();
db.zipcodes.insert([
{ city:"birmingham", population:1500000, state:"AL" },
{ city:"London", population:10000, state:"ON" },
{ city:"New York", population:1000, state:"NY" },
{ city:"Denver", population:100, state:"CO" },
{ city:"Los Angeles", population:1000000, state:"CA" },
{ city:"San Francisco", population:2000000, state:"CA" },
]);
db.zipcodes.runCommand("aggregate", { pipeline: [
{ $match: { state: "CA" } }, // WHERE state='CA'
{ $group: {
_id: "$city", // GROUP BY city
population: { $sum: "$population" }, // SUM(population) as population
}},
]});
produces
{
"result" : [
{
"_id" : "San Francisco",
"population" : 2000000
},
{
"_id" : "Los Angeles",
"population" : 1000000
}
],
"ok" : 1
}
you could try:
db.zipcodes.group( { key: { state:1 } ,
reduce: function(curr, result) {
result.total += curr.pop;
result.city.push( { _id: curr.city, pop: curr.pop } ); },
initial: { total: 0, city:[] },
finalize: function (result) {
for (var idx in result.city ) {
result.city[idx].ratio = result.city[idx].pop/result.total;
}
} } )