after saving in mongoose {strict : false},can't edit after findOne() - get

this is my schema
name : String,
phone : String,
address : String
mongoose.model("user",userSchema);
var user = mongoose.model("user");
var newUser = new user({name : "d",phone : "p",address : "q"});
newUser.save();
newUser.findOne({_id : "dsklfj98908"},function(err,result){
result.set('unlockGames',"puzzle",[String],{strict : false});
result.save();
});
working wonderful,until i want to change one more time:
//NOT WORKING 1
newUser.findOne({_id : "dsklfj98908"},function(err,result){
result.get("unlockGames").push("Gag jan stees");
result.save();
});
//NOT WORKING 2
newUser.findOne({_id : "dsklfj98908"},function(err,result){
var unlockGames = result.get("unlockGames").push("Gag jan stees");
result.set('unlockGames',unlockGames,[String],{strict : false});
result.save();
});
Help please!)

now it's working
var game = "es chlnei duq inch eiq anelu";
var unlockGames = result.get("unlockGames");
result.unlockGames = unlockGames.push(game);
result.markModified('unlockGames');
that's it);

Related

mongodb issue when using .find()

I am using MongoDB for the first time and I came across an error that I could not solve.
Here is my code:
const mongoose = require('../../common/services/mongoose.service').mongoose;
const Schema = mongoose.Schema;
const functions = require('./functions');
const userSchema = new Schema({
email: String,
password: String,
number: String,
state: Boolean
});
userSchema.virtual('id').get(function () {
return this._id.toHexString();
});
// Ensure virtual fields are serialised.
userSchema.set('toJSON', {
virtuals: true
});
userSchema.findById = function (cb) {
return this.model('Users').find({id: this.id}, cb);
};
const User = mongoose.model('Users', userSchema);
exports.findByEmail = (email) => {
//console.log('hello'); //this works btw
return User.find({email: email});
};
So in the code above, findByEmail works fine since hello is logged. However, when it gets to return User.find, I get this error: SyntaxError: Unexpected token g in JSON at position 0.
This is what is currently in the DB:
{
"_id" : ObjectId("6026b813f1828a51f8979616"),
"email" : "gogo#gmail.com",
"password" : "GLImDln1xMKfKS/E99s8qg==$Es3PIHD95vV89973Xq4RecveYMEf22PCH/pFtG1+xq4Gtc4DelA/JXlRNcOR11Rfv/J1uaZCuOplsEmHhY0ehQ==",
"number" : "6969",
"state" : true,
"__v" : 0
}
I input gogo#gmail.com. Does anyone know what I am doing wrong? It would mean a lot to me. I am using node/vue btw.
Error occurs within findByEmail when I run it

Push data to an embedded array using mongoose

My Schema look like this
var Company ={
Name
Email
Location
Industry
Creator
PostedJobs : [{
JobName
JobType
JobLocation
JobSalary
Applicants : [{
Name
Status
}]
}]
}
to push job here is my route code which is working
router.post('/:name' , isLoggedIn , function(req , res , next) {
var JobName = req.body.JobName;
var JobType = req.body.JobType;
var JobLocation = req.body.JobLocation;
var Salary = req.body.Salary;
var postedJob = {JobName : JobName, JobType : JobType, JobLocation : JobLocation, JobSalary:Salary};
var name = req.params.name;
Company.findOne({Name : name}).then(function(Company) {
Company.PostedJobs.push(postedJob);
Company.save();
req.flash('sucess_msg' , 'Job Added Sucessfully');
res.render('dashboard',{
"Company" : Company
});
});
});
now i want to push applicants on apply button
apply code is
router.get('/:id/apply' , isLoggedIn , function(req , res , next) {
var appicant = { Name : req.user.FirstName,
Status : "Applied"
};
Company.find({'PostedJobs._id' : req.params.id}).then(function(job) {
Company.PostedJobs.Applicants.push(applicant);
Company.save();
req.flash('sucess_msg' , 'Job Added Sucessfully');
res.redirect('/jobs');
});
});
i also tried
which is not working and i wont know what to do with this
Can you try this? when pushing applicants.
Company.PostedJobs[0].Applicants.push(applicant);

MongoDB and mongoose: how to add an object if it doesn't already exist

I am having some trouble with mongoDB/mongoose and node.js. I am used to SQL, and mongoDB is...hard! Here is my schema:
var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
var itemSchema= mongoose.Schema({
item_info : {
user_id : Number,
location : String,
item_id : Number,
title : String
},
item_hist : {
user_id : Number,
location : String,
item_id : Number,
founddate : String
}
});
module.exports = mongoose.model('item', itemSchema);
And I can add a new item by doing this:
var item= require('./app/models/item');
var item= new item();
item.item_info.user_id = 12345;
item.item_info.location = 'This address';
item.item_info.item_id = 4444;
item.item_info.title = 'New item';
item.save(function(err)
{
if (err) throw err;
});
What I want to be able to do is say: "look for an item with item_info.item_id 5555. if it exists, do nothing. if it doesn't exist, then add it to the database." I've read through so much mongodb and mongoose documentation, but between using dot notation and accessing through nodejs instead of command line mongodb, I still can't figure out how to do this. SQL seemed so much easier!
Just use this -
var query = { user_id: 12345, location: "This address", item_id: 4444, title: "New item" },
options = { upsert: true };
Model.findOneAndUpdate(query.item_id, query, options, function(error, result) {
if (error) return;
// do something with the document
});

fetch all the users with specific attribute

Hey everybody Im new with node and mongo hope for your help with it.
I defined a user schema with mongoose:
var userSchema = mongoose.Schema({
local : {
email : String,
password : String,
name : String
},
facebook : {
id : String,
email : String,
token : String,
firstName : String,
familyName : String
},
google : {
id : String,
email : String,
token : String,
firstName : String,
familyName : String
}});
Im tring to fetch all the users (from local google and facebook) with specific email.
How do I write it ?
I tried something like:
var User = require('./models/user');
app.get('/api/user/:email',function(req,res){
User.findOne({'email':req.params.email},function(err,user){
res.json(user);
})
});
How do I fix it ?
Thanks.
Add
module.exports = mongoose.model("User", userSchema);
to your schema file.
Then try the following:
var User = require('./models/user');
app.get('/api/user/:email',function(req,res){
User.findOne({"local.email": req.params.email}, function(err,user){
res.json(user);
});
});
Or for all three:
var User = require('./models/user');
app.get('/api/user/:email',function(req,res){
User.findOne({$or: [
{"local.email": req.params.email},
{"facebook.email": req.params.email},
{"google.email": req.params.email}
]}, function(err,user){
res.json(user);
});
});

Mongoose mapReduce Error: OUT parameter must be defined

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.

Resources