Difference between saved/load json object in Mongoose - javascript

I have a problem saving a json object in mongodb(Mongoose) so when i make the insert everything is ok, but when i make the request of the same object, Mongoose return a modified json. Its like Mongoose autocomplete the twitter field and i dont know why.
Here is my code:
UserSchema = mongoose.Schema({
firstName: String,
lastName: String,
email: String,
salt: String,
hash: String,
twitter:{
id: String,
email: String,
name: String
},
facebook:{
id: String,
email: String,
name: String,
username: String,
photo: String,
gender: String
}
});
I save json in my database:
User.create({
email : profile.emails[0].value,
facebook : {
id: profile.id,
email: profile.emails[0].value,
name: profile.displayName,
username: profile.username,
photo: profile.photos[0].value,
gender: profile.gender
}
}, function(err, user){
if(err) throw err;
// if (err) return done(err);
done(null, user);
});
But i when mongoose return a json.
Mongoose generated a field in the json. twitter:{} <----
I dont know why, can anyone lend me a hand?

If you look at the document saved to the MongoDB, you'll see that the twitter object isn't actually present unless the properties of the sub object are set. The object is created so that you can conveniently set properties without needing to worry about creating the sub/nested object. So you can do this:
var user = new User();
user.twitter.id = 'wiredprairie';
user.save();
Results:
{ "_id" : ObjectId("522259394eb9ed0c30000002"),
"twitter" : { "id" : "wiredprairie" }, "__v" : 0 }
And if you went one step further and wanted a more "pure" view of the data, you could use toJSON on the Mongoose model instance:
console.log(user.toJSON());
results:
{ _id: 522259ad3621834411000001, twitter: { id: 'wiredprairie' } }

Related

Grails - Is it possible to bind the fields within a JS object that has been posted (AJAX)

Is it possible to customise data binding such that I can simply pass an object to an AJAX post request rather than having to list out all of the params (as per comment)?
The commented out line binds as expected.
submitNewUser: function () {
const user = this.form
this.$http.post(`https://localhost:8443/api/saveUser`,
{data: user})
// {userName: user.userName, firstName: user.firstName, lastName: user.lastName, title: user.title, email: user.email})
.then(response => {
let user = response.data
this.users.push(user)
this.user = {userName: '', firstName: '', lastName: '', title: '', email: ''}
})
.catch(ex => console.error('Unable to save user', ex))
}
Grails command object:
class SaveUserCommand {
String userName
String firstName
String lastName
String title
String email
}
The form object:
form: {
userName: null,
firstName: null,
lastName: null,
title: null,
email: null,
}
The JSON data structure being sent (as retrieved from devtools);
{
data: {
userName: "New_user5"
email: "myemail#myuser.com"
firstName: "New"
lastName: "User"
title: "User Admin"
}
}
the JSON data structure that results from the commented out line of code;
{
userName: "New_user5"
email: "myemail#myuser.com"
firstName: "New"
lastName: "User"
title: "User Admin"
}
I hope this clarifies the question somewhat.
Are you sure your command object is validateable, i.e. is it either in the same file as the controller, or if not, is it annotated with #Validateable?
If you're sure it's validateable, can you execute JSON.stringify(user) in the browser console (dev tools), so we can see the structure of the data you're sending?
Update
It seems this is the structure of the data you're sending:
{
user: {
userName: "New_user5"
email: "myemail#myuser.com"
firstName: "New"
lastName: "User"
title: "User Admin"
}
}
And you're trying to bind it to:
class SaveUserCommand {
String userName
String firstName
String lastName
String title
String email
}
Binding is failing because the objects don't have the same properties, so you have two choices:
Option 1: Change the request data
Send this instead:
{
userName: "New_user5"
email: "myemail#myuser.com"
firstName: "New"
lastName: "User"
title: "User Admin"
}
I would expect this to be the easier of the 2 options, you probably just need to replace:
{data: user}
with:
{data: this.form.user}
Option 2: Change the command object
Bind the request data to this instead
#Validateable
class SaveUserCommand {
UserData user
}
#Validateable
class UserData {
String userName
String firstName
String lastName
String title
String email
}

Document not updated in findOneAndUpdate

I have a post route that receives data from a PUT request in an express app that aims to update a mongoose document based on submitted form input. The "Base" model is Profile, and I have two discriminator models Helper and Finder that conditionally add fields to the Profile schema (see below for details).
Thus, req.body.profile will contain different fields depending on the discriminator it's associated with, but will always contain the fields (username, email city, accountType) present in the "base" model, Profile.
Before I send my PUT request, an example of a document in Profile looks like this:
{ jobTitle: '',
lastPosition: '',
email: '',
city: '',
accountType: 'helper',
_id: 5c77883d8db04c921db5f635,
username: 'here2help',
__v: 0 }
This looks good to me, and suggests that the model is being created as I want (with base fields from Profile, and those associated with the Helper model - see below for models).
My POST route then looks like this:
router.put("/profile/:id", middleware.checkProfileOwnership, function(req, res){
console.log(req.body.profile);
Profile.findOneAndUpdate(req.params.id, req.body.profile, function(err, updatedProfile){
if(err){
console.log(err.message);
res.redirect("/profile");
} else {
console.log(updatedProfile);
res.redirect("/profile/" + req.params.id);
}
});
});
The information I receive from the form (console.log(req.body.profile)) is what I expect to see:
{ accountType: 'helper',
username: 'here2help',
email: 'helpingU#me.com',
city: 'New York',
jobTitle: 'CEO',
lastPosition: 'sales rep'}
However, after updating the document with req.body.profile in Profile.findOneAndUpdate(), I do not see my returned document updated:
console.log(updatedProfile)
{ jobTitle: '',
lastPosition: '',
email: 'helpingu#me.com',
city: 'New York',
accountType: 'helper',
_id: 5c77883d8db04c921db5f635,
username: 'here2help',
__v: 0 }
So, the fields that are defined in my 'Base' model (ie those defined in ProfileSchema - see below) are being updated (e.g. city), but those that are in my discriminators are not - see below.
The updated information is clearly present in req, but is not propagated to the Profile model - How can this be?
I've also tried using findByIdAndUpdate but I get the same result.
Here are the Schemas I'm defining:
Profile - my "base" schema:
var mongoose = require("mongoose");
var passportLocalMongoose = require("passport-local-mongoose");
var profileSchema = new mongoose.Schema({
username: String,
complete: { type: Boolean, default: false },
email: { type: String, default: "" },
city: { type: String, default: "" }
}, { discriminatorKey: 'accountType' });
profileSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("Profile", profileSchema);
Finder
var Profile = require('./profile');
var Finder = Profile.discriminator('finder', new mongoose.Schema({
position: { type: String, default: "" },
skills: Array
}));
module.exports = mongoose.model("Finder");
Helper
var Profile = require('./profile');
var Helper = Profile.discriminator('helper', new mongoose.Schema({
jobTitle: { type: String, default: "" },
lastPosition: { type: String, default: "" }
}));
module.exports = mongoose.model("Helper");
This is my first attempt at using discriminators in mongoose, so it's more than possible that I am setting them up incorrectly, and that this is the root of the problem.
Please let me know if this is unclear, or I need to add more information.
It matters what schema you use to query database
Discriminators build the mongo queries based on the object you use. For instance, If you enable debugging on mongo using mongoose.set('debug', true) and run Profile.findOneAndUpdate() you should see something like:
Mongoose: profiles.findAndModify({
_id: ObjectId("5c78519e61f4b69da677a87a")
}, [], {
'$set': {
email: 'finder#me.com',
city: 'New York',
accountType: 'helper',
username: 'User NAme', __v: 0 } }, { new: true, upsert: false, remove: false, projection: {} })
Notice it uses only the fields defined in Profile schema.
If you use Helper, you would get something like:
profiles.findAndModify({
accountType: 'helper',
_id: ObjectId("5c78519e61f4b69da677a87a")
}, [], {
'$set': {
jobTitle: 'CTO',
email: 'finder#me.com',
city: 'New York',
accountType: 'helper ',
username: 'User Name', __v: 0 } }, { new: true, upsert: false, remove: false, projection: {} })
Notice it adds the discriminator field in the filter criteria, this is documented:
Discriminator models are special; they attach the discriminator key to queries. In other words, find(), count(), aggregate(), etc. are smart enough to account for discriminators.
So what you need to do when updating is to use the discriminator field in order to know which Schema to use when calling update statement:
app.put("/profile/:id", function(req, res){
console.log(req.body);
if(ObjectId.isValid(req.params.id)) {
switch(req.body.accountType) {
case 'helper':
schema = Helper;
break;
case 'finder':
schema = Finder;
break;
default:
schema = Profile;
}
schema.findOneAndUpdate({ _id: req.params.id }, { $set : req.body }, { new: true, upsert: false, remove: {}, fields: {} }, function(err, updatedProfile){
if(err){
console.log(err);
res.json(err);
} else {
console.log(updatedProfile);
res.json(updatedProfile);
}
});
} else {
res.json({ error: "Invalid ObjectId"});
} });
Notice, above is not necessary when creating a new document, in that scenario mongoose is able to determine which discriminator to use.
You cannot update discriminator field
Above behavior has a side effect, you cannot update the discriminator field because it will not find the record. In this scenario, you would need to access the collection directly and update the document, as well as define what would happen with the fields that belong to the other discriminator.
db.profile.findOneAndUpdate({ _id: req.params.id }, { $set : req.body }, { new: true, upsert: false, remove: {}, fields: {} }, function(err, updatedProfile){
if(err) {
res.json(err);
} else {
console.log(updatedProfile);
res.json(updatedProfile);
}
});
Please add option in findOneAndUpdate - { new: true };
In Moongose findOneAndUpdate() Method have four parameters
like
A.findOneAndUpdate(conditions, update, options, callback) // executes
And you need to execute like this
var query = { name: 'borne' };
Model.findOneAndUpdate(query, { name: 'jason bourne' }, options, callback)
or even
// is sent as
Model.findOneAndUpdate(query, { $set: { name: 'jason bourne' }}, options, callback)
This helps prevent accidentally overwriting your document with { name: 'jason bourne' }.

node.js mongoose TypeError: set is not a function

Pretty new to Node.js and Mongoose.
Trying to perform a basic set action after finding the relevant object, however I get the following error:
TypeError: {found object}.set is not a function.
The following is the code causing the error:
UserProfile.find({"user": req.params.id}, function (err, userProfile) {
if (err) {
console.log("Saving User profile - Error finding user");
} else { // no error
if (userProfile) { // if userProfile is found
console.log("Saving User profile - userProfile found for user: " + userProfile);
userProfile.set ({
gender: req.body.gender,
dob: req.body.dob,
phone: req.body.phone,
phone2: req.body.phone2,
state: req.body.state,
country: req.body.country
});
}
}
});
The following is the error i receive:
TypeError: userProfile.set is not a function
If I'm trying to use the "set" function on a new object created based on the same model, it works with no issue
var userProfile = new UserProfile ();
userProfile.set ({
gender: req.body.gender,
dob: req.body.dob,
phone: req.body.phone,
phone2: req.body.phone2,
state: req.body.state,
country: req.body.country
});
The following is the model:
var mongoose = require("mongoose");
var UserProfileSchema = new mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
gender: String,
phone: String,
phone2: String,
dob: Date
});
module.exports = mongoose.model ("UserProfile", UserProfileSchema);
Use findOne not find. The former returns an object as the 2nd argument in the callback, the latter returns an array as the 2nd argument in the callback.
.find returns an array of documents. try using .findOne which returns the first found document

Querying from [array of objects] with mongoose find

I have two Mongo schemas defined as follows:
var userSchema = new mongoose.Schema({
email: String,
password: String, //hash created from password
firstName: String,
lastName: String,
comment:{userComment:String,adminComment:String},
postalAddress: String,
city: String,
state: String,
country: String,
institution: String,
privilege: {type: String, enum:['normal','chair','admin']},
status: {type:String, enum: ['granted','removed','pending']},
myConference:[{type:Schema.Types.ObjectId,ref:'Conference'}],
mySubmission:[{type:Schema.Types.ObjectId,ref:'Submission'}]
});
var conferenceSchema = new mongoose.Schema({
conferenceTitle: {type:String},
conferenceDescription: String,
conferenceStartDate:{type:Date, default: Date.now},
submissionEndDate:{type:Date},
reviewEndDate:{type:Date},
**conferenceMembers:[{type:Schema.Types.ObjectId,ref:'User'}]**,
conferenceSubmissions:[{type:Schema.Types.ObjectId,ref:'Submission'}],
createdBy:{type:Schema.Types.ObjectId,ref:'User'},
//chairMembers:[{type:Schema.Types.ObjectId,ref:'User'}],
department:String
});
Requirement: I want to fetch all the Conference objects which match a certain _id i.e. unique for each 'User' schema object.
conferenceMembers is an array of 'User' objects
What I did:
It's a POST:
var userId=req.body.userId
**Conference.find({userId: {$in: [Conference.conferenceMembers]}},function(err,conf){**
if(err){
return res.send(500, err);
}
return res.send(200,conf);
But, the filter doesn't seem to work here, I tried with $elemMatch as well but no luck.
To fetch all the documents which has specific userId in conferenceMembers, you can do this:
Conference.find({conferenceMembers : userId}).exec(function(err,conf){...});
if you want to populate the users too you can use mongoose populate.
Conference.find({conferenceMembers : userId}).populate('conferenceMembers').exec(function(err,conf){...});

Mongoose populate documents

I got 3 database models in mongoose that looks like this:
//profile.js
var ProfileSchema = new Schema({
username: { type: String, required: true },
password: { type: String, required: true },
matches: [{ type: Schema.Types.ObjectId, ref: 'Match' }]
});
//match.js
var MatchSchema = new Schema({
scores: [{ type: Schema.Types.ObjectId, ref: 'Score', required: true }],
});
//score.js
var ScoreSchema = new Schema({
score: {type: Number, required: true},
achivement: [{type: String, required: true}],
});
And I try to populate a profile with
Profile.findOne({ _id: mongoose.Types.ObjectId(profile_id) })
.populate('matches')
.populate('matches.scores')
.exec(function(err, profile) {
if (err) {...}
if (profile) {
console.log(profile);
}
});
The matches get populated but I dont get the scores in matches to populate. Is this not supported in mongoose or do I do something wrong? Populate gives me this:
{
user_token: "539b07397c045fc00efc8b84"
username: "username002"
sex: 0
country: "SE"
friends: []
-matches: [
-{
__v: 1
_id: "539eddf9eac17bb8185b950c"
-scores: [
"539ee1c876f274701e17c068"
"539ee1c876f274701e17c069"
"539ee1c876f274701e17c06a"
]
}
]
}
But I want to populate the score array in the match array. Can I do this?
Yes, you are right. I tried using Chaining of populate I got same output.
For your query please use async.js and then populate by the method mentioned below.
For more details please have a look at this code snippet. It is a working, tested, sample code according to your query. Please go through the commented code for better understanding in the code below and the link of the snippet provided.
//Find the profile and populate all matches related to that profile
Profile.findOne({
_id: mongoose.Types.ObjectId(profile_id)
})
.populate('matches')
.exec(function(err, profile) {
if (err) throw err;
//We got the profile and populated matches in Array Form
if (profile) {
// Now there are multiple Matches
// We want to fetch score of each Match
// for that particular profile
// For each match related to that profile
async.forEach(profile.matches, function(match) {
console.log(match, 'match')
// For each match related to that profile
// Populate score achieved by that person
Match.find({
_id:match.id
})
.populate('scores', 'score')
.exec(function (err, score) {
if (err) throw err;
// here is score of all the matches
// played by the person whose profile id
// is passed
console.log(score);
})
})
}
});
Profile.findOne({ _id: mongoose.Types.ObjectId(profile_id) })
.populate('matches.scores')
.exec(function(err, profile) {
if (err) {...}
if (profile) {
console.log(profile);
}
});

Categories

Resources