Mongoose mapReduce Error: OUT parameter must be defined - node.js

I am using mongoose framework to communicate with the mongodb. Now i am in the situation to join the two collections using mapReduce. I have followed this tutoria "http://blog.knoldus.com/2014/03/12/easiest-way-to-implement-joins-in-mongodb-2-4/" to get it done.
I have successfully done with join using mapReduce in mongoDB Shell using robomongo.
Same i am trying with mongoose frame work but its giving me error that Out parameter must be defied.
The code sample what i have done.
This is the collection schema for User profile:
var User = new mongoose.Schema({
name : {
first : {type : String},
last : {type : String}
},
title : {type : String},
userName : {type : String, unique : true},
profileImgUrl : {type : String},
mojo : Number
});
this is the collection schema for the testimonials:
var Testimonials = new mongoose.Schema({
from : String,
to : String,
text : String
});
This is the code using mongoose, nodejs:-
var mapTalent = function () {
var output= {userName : this.userName,firstname:this.name.first, lastname:this.name.last , profileImgUrl : this.profileImgUrl, mojo : this.mojo, text : null}
emit(this.userName, output);
};
var mapTestimonial = function () {
var output = {fromTalentName : this.fromTalentName, firstname:null, lastname:null, profileImgUrl : null, mojo : null, text : this.text}
emit(this.text, output);
};
var reduceF = function(key, values) {
var outs = {firstname:null, lastname:null , profileImgUrl:null, text : null, mojo:null};
values.forEach(function(v){
if(outs.firstname ==null){
outs.firstname = v.firstname
}
if(outs.lastname ==null){
outs.lastname = v.lastname
}
if(outs.profileImgUrl ==null){
outs.profileImgUrl = v.profileImgUrl
}
if(outs.mojo ==null){
outs.mojo = v.mojo
}
if(outs.text == null){
outs.text = v.text
}
});
return outs;
};
result = Testimonials.mapReduce(mapTestimonial, reduceF, {out : {reduce : "Talent_Testimonials"}});
result = Talent.mapReduce(mapTalent, reduceF, {out : {reduce : "Talent_Testimonials"}});
Here the error is thrown as " the out option parameter must be defined".
What i am doing wrong here i am not getting. This same works in mongoDB shell.

mapReduce can't be called the same way in Mongoose as it is in the shell.
For Mongoose, the call would need to look like:
Testimonials.mapReduce({
map: mapTestimonial,
reduce: reduceF,
out : {reduce : "Talent_Testimonials"}
}, function (err, results) { ... });
See the docs here.

Related

how to find the document in mongodb database which contain multiple collections in a schema

Below is my MongoDB schema.
var userSchema = mongoose.Schema({
local : {
username :String,
name : String,
email : String,
password : String,
},
facebook : {
id : String,
token : String,
email : String,
name : String
},
twitter : {
id : String,
token : String,
displayName : String,
username : String
},
google : {
id : String,
token : String,
email : String,
name : String
}
});
I want to find the document which contains username which I specify in the argument and to achieve it I write below line of code
module.exports.getUserByUsername = function(username, callback){
var u = new User();
var query = {u.local.username: username};
User.findOne(query, callback);
}
but it says unexpected token.What should I have to do?
Your query needs to provide the name of the field to match against using a dot-notation string:
var query = {'local.username': username};

How do I perform a find query in Mongoose?

i have a collection of Ebooks data in mongodb like
{
"_id" : ObjectId("58b56fe19585b10cd42981d8"),
"cover_path" : "D:\\Ebooks\\uploads\\ebooks\\cover\\1488285665748-img1-700x400.jpg",
"path" : "D:\\Ebooks\\uploads\\ebooks\\pdf\\1488285665257-Webservices Natraz.pdf",
"description" : "ebook",
"title" : "book name",
"tag" : [
"Hindi",
"Other"
],
"__v" : NumberInt(0)
}
Now i want to search something if keyword is little bit match from "title:" then show all related books object.
My Mongoose schema is :-
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var EbookSchema = new Schema({
title: {type:String},
description: {type:String},
path: {type:String,required:true},
cover_path: {type:String,required:true},
tag: [{ type: String }]
});
module.exports = mongoose.model('Ebook', EbookSchema);
I try :-
app.get('/ebook?search=',function(req,res){
var search_key = req.param('search');
Ebook.find(title:'search',function(err, ebooks) {
if (err)
res.send(err);
res.json(ebooks);
});
});
but i found null how can i do ? i only want when i search a little-bit keyword i found all related object .
Try wrapping your query in curlies, Mongoose expects an object as the query.
app.get('/ebook?search=',function(req,res){
var search_key = req.param('search');
Ebook.find({title: search_key})
.then(ebooks => res.json(ebooks))
.catch(err => res.status(404).json({ success: false }));
});

Maximum call stack exceeded mongoose

I'm trying to save documents into a mongodb collection using mongoose/node.js with the schema ,
var userSchema = {
userName : String,
userId : Number,
Location : [{Country : String}]
};
var mySchema = {
userData : userSchema,
title : String
};
var MyModel = mongoose.model('MyModel' , mySchema);
However on ,
req.MY_user = JSON.parse(res.body); // Response from an API
MyModel.update({title : 'sometitle'} , {userData : req.MY_user , title : 'sometitle'} ,
{upsert : true} ,
function(err , raw){ ... });
I get an error, Maximum call stack exceeded.
Strangely, it works fine on my local machine running Mac.
Problem arises when deployed to linux/windows.
Any solutions please ?
Eg Response :
req.MY_user = {
userName : 'John',
userId : 12345,
Location : [{Country : 'Rus'} , {Country : 'Ind'}]};
Update , adding error.stack,
Range Error : at Function.isArray (native),
at shouldFlatten node_modules/mongoose/lib/services/common.js 81:13
at modifiedPaths node_modules/mongoose/lib/services/common.js 65:7
(above line is repeated multiple times)

mongoose multiple parameter create with middleware

I have a problem with Creating with Multiple Parameter using Middleware validation,
here is my Schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Order = mongoose.Schema({
orderCode : {type: String, default : null, unique: true},
price : {type : Number, default : 0},
createdAt : {type : Date, default : new Date()},
updatedAt : {type : Date, default : new Date()}
});
Order.pre("save", function(next, done){
var self = this;
var templateDate = new Date().toISOString().slice(0,10).replace(/-/g,"");
mongoose.models["Order"].find({}, function(err, orders){
if(err){
done(err)
} else {
var queue = orders.length + 1;
self.orderCode = "#"+templateDate+queue;
done();
next();
}
});
});
and here is my parameters and code,
[{"price":10000}, {"price":15000}]
models.Order.create(parameters, function(err){
...
});
without Using Middleware, I have created 2 data based on this parameter, but when I'm using Middleware, it just created only one but in the arguments it shows 2.
any help? thanks

Node.js - How to create a unique id with mongoose db

I am working with Twitter authentication and want to store the twitter id as unique key in mongodb. However i see multiple entries with the same id. Here's my schema and code
Schema:
var TwitterSchema = new Schema({
accessToken: String,
accessTokenSecret: String,
name: String,
twitterId: { type: String, required: true, index: { unique: true, sparse: true } }
});
Code:
mongoose.connect('mongodb://localhost/twd')
mongoose.model('Post', TwitterSchema);
var Post = mongoose.model('Post');
var post = new Post();
post.accessToken = accessToken
post.accessTokenSecret = accessTokenSecret
post.name = twitterUserData.name
post.twitterId = twitterUserData.id
post.save(function(err){
if (err){
throw err;
promise.fail(err);
}
console.log('saved');
mongoose.disconnect();
});
promise.fulfill(post);
DB shell output
> db.posts.find();
{ "twitterId" : "21475255", "name" : "MMMK", "accessTokenSecret" : "ZYhiXMWfXvSr1aaCB93hgU243j8aapP0ALdSFlWEE", "accessToken" : "22475255-9YvKMceUInUIxcEtKAK0oMRRG2ZZxn5c52vnwPw", "_id" : ObjectId("4feddf6155203990e000001") }
{ "twitterId" : "21475255", "name" : "MMMK, "accessTokenSecret" : "ZYhiXMWfXvSr1aaCB93hgU2438aapP0ALdSFlWEE", "accessToken" : "22475255-9YvKMceUInUIxcEtKAK0oMRRG2ZZxn5c52vnwPw", "_id" : ObjectId("4feddf7b5905a1a10e000001") }
My guess is either the index isn't being created in MongoDB, or the index with the same name already exits. If it already exists, mongoose will use ensureIndex to create it, but that won't override/redefine it if it already exists. Use the mongo js shell to see if it exists, then try dropping it, restarting mongod, and running your node.js code again.
http://www.mongodb.org/display/DOCS/Indexes#Indexes-CreationOptions

Resources