Empty objects using app.post and AngularJS + mongoose on node.js - node.js

My REST API is posting empty objects.
I am getting the value from req.body.name
If I log it console.log(req.body.name); I get the value on my console.
POST:
{ name: 'typing any name', status: null }
typing any name
So the workflow between my frontend (angular.js), the form and the backend (node.js, express, mongoose) seems to work. Now I POST the value, but I get an empty object in my mongoDB.
{"_id":"543a50a974de6e2606bd8478","__v":0}
app.post('/api/offers', function (req, res){
var offer;
console.log("POST: ");
console.log(req.body);
console.log(req.body.name);
offer = new OfferModel({
name: req.body.name,
value: req.body.value,
title: req.body.title,
content: req.body.content,
});
offer.save(function (err) {
if (!err) {
return console.log("created offer" + req.body.name);
} else {
return console.log(err);
}
});
return res.send(offer);
});
And here is the model:
var offerSchema = mongoose.Schema({
offer : {
name : String,
value : String,
title : String,
content : String,
image : String,
start : String,
end : String,
targets : String,
beacons : String,
published : String
}
});
var OfferModel = mongoose.model('Offer', offerSchema);

Schema is incorrect, must be like this:
var offerSchema = mongoose.Schema({
name : String,
value : String,
title : String,
content : String,
image : String,
start : String,
end : String,
targets : String,
beacons : String,
published : String
});

Related

Express: Embed document in the existing document

I am developing an application in Express, Node and Mongo being the database. I have a collection users, and user can have mutiple registered-IDs. It like a one-to-many relationship. I m trying to embed a document in the user collection like this:
post(function (req, res, next) {
var pid=req.body.pid;
var sid=req.body.sid;
var rfname=req.body.rfname;
var des=req.body.des;
var brand=req.body.brand;
var model=req.body.model;
var serial=req.body.serial;
var location=req.body.location;
var arr={pid: 'pid', sid: 'sid', rfname: 'rfname' ,des: 'des', brand: 'brand', model: 'model' ,serial: 'serial', location: 'location'};
mongoose.model('User').findOne({'pemail': req.session.email}, function (err, user){
if(err){
} else {
user.registeredId = arr;
user.save(function(err){
if(err){
} else {
res.render('user/register', {'success': 'dfhlaksdhfh'});
}
})
}
});
}
My user schema is like this:
var mongoose = require('mongoose');
var userSchema = new mongoose.Schema({
email: String,
password: String,
fname: String,
lname: String,
plang: String,
slang: String,
country: String,
state: String,
city: String,
postalcode: String,
address1: String,
address2: String,
pemail: String,
semail: String,
age: String,
gender: String,
pphone: String,
sphone: String,
q1: String,
a1: String,
q2: String,
a2: String,
cfname: String,
clname: String,
cemail: String
});
mongoose.model('User', userSchema);
Guide me, what am i doing wrong, because it does not embed document in the existing document. Do I need to define that in schema, if so, then how?
In your schema definition, the field registeredId is not defined and by default through the strict option, Mongoose ensures that values passed to your model constructor that were not specified in our schema do not get saved to the db, hence it is not creating the modified document.
You can either explicitly define the field in your schema or set the strict option to false in your schema definition:
// set to false..
var userSchema = new Schema({..}, { strict: false });
and then implement one of the findAndModify() methods like findOneAndUpdate() to update your user document by pushing the new object to the new array field registeredId. So you could re-write your post function as:
post(function (req, res, next) {
var User = mongoose.model('User'),
pid=req.body.pid,
sid=req.body.sid,
rfname=req.body.rfname,
des=req.body.des,
brand=req.body.brand,
model=req.body.model,
serial=req.body.serial,
location=req.body.location,
arr = {
'pid': pid,
'sid': sid,
'rfname': rfname,
'des': des,
'brand': brand,
'model': model,
'serial': serial,
'location': location
},
condition = { 'pemail': req.session.email },
update = {
"$push": { 'registeredId': arr }
};
User.findOneAndUpdate(
condition,
update,
function (err, doc){
if(err){}
else {
// doc contains the modified document
res.render('user/register', {'success': 'dfhlaksdhfh'});
}
}
);
});

Mongoose object id is null

I'm creating an object Registration (a Mongoose Schema) and I need to set its Id in User with this line: registrationId: registration._id});
However, the Id is still null, even though it's the callback function? When I check the database the Registration has and Id of course, but not in the callback. How can I set the Id of the Registration in User?
Edit2: changed to minimal example. This prints out two times null.
exports.create = function(req, res) {
Registration.create(req.body, function(err, registration) {
if(err) { return handleError(res, err); }
console.log(registration._id);
console.log(registration.id);
return res.json(201, registration);
});
};
Edit: this is the schema (I left out some fields that are not required):
'use strict';
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var RegistrationSchema = new Schema({
isReservation: Boolean,
//Id of the trip
tripId: String,
//socialMutuality
codeGerechtige: String,
socialMutualityNumberParent1: String,
socialMutualityNumberParent2: String,
//contact
userId: String,
firstnameContact: String,
lastnameContact: String,
emailContact: String,
streetContact: String,
streetNumberContact: String,
zipcodeContact: String,
busContact: String,
cityContact: String,
phoneContact: String,
gsmContact: String,
socialSecurityNumberContact: String,
//coordinats of person that pays
//child information
//emergency contacts
emergencyContacts: [{
firstName: String,
lastName: String,
phone: String
}],
extraInfo: String
});
module.exports = mongoose.model('Registration', RegistrationSchema);
Problem and solution: the problem was the client sending an attribute _id = null, and that's why MongoDB/Mongoose didn't update the id.
removing _id from req.body fixed my issue.
if(req.body._id === null) {
delete req.body._id;
}
There must be something else going on in your code which is effecting this. This example works as expected for me:
'use strict';
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
mongoose.connect('mongodb://localhost/createid');
var RegistrationSchema = new Schema({
isReservation: Boolean,
//Id of the trip
tripId: String,
//socialMutuality
codeGerechtige: String,
socialMutualityNumberParent1: String,
socialMutualityNumberParent2: String,
//contact
userId: String,
firstnameContact: String,
lastnameContact: String,
emailContact: String,
streetContact: String,
streetNumberContact: String,
zipcodeContact: String,
busContact: String,
cityContact: String,
phoneContact: String,
gsmContact: String,
socialSecurityNumberContact: String,
//coordinats of person that pays
//child information
//emergency contacts
emergencyContacts: [{
firstName: String,
lastName: String,
phone: String
}],
extraInfo: String
});
var Registration = mongoose.model('Registration', RegistrationSchema);
var reg = {
userId: '1234',
tripId: '2345',
firstnameContact: 'Timothy',
lastnameContact: 'Strimple',
emailContact: 'tim#tstrimple.com'
};
Registration.create(reg, function(err, registration) {
if(err) { throw err; }
console.log(registration._id);
});
I get a valid id written out to the console.

mongoose .push embedded docs in an embedded model?

Would like to .push fields of an embedded structure into an embedded model document on a .push method.
http://mongoosejs.com/docs/2.7.x/docs/embedded-documents.html
The console errors this though: SyntaxError: Unexpected token .
..for pushing bar.this : req.body.this, when concatenating for the embed in the embedded model
The models look like this:
var OneModel = new Schema({
foo: String,
bar: {
this : String,
that : Number,
}
});
var TwoModel = new Schema({
foo: String,
bar: {
this : String,
that : Number,
},
modelone: [OneModel]
});
And the NodeJS API looks this:
var ModelsOneTwo = require('./app/models/modelsonetwo');
router.route('/modeltwo/:modeltwo_id')
// update TwoModel with this _id
//(accessed at PUT http://localhost:4200/api/v1/modeltwo/:modeltwo_id)
.put(function(req, res) {
ModelsOneTwo.findById(req.params._id, function(err, modeltwo) {
if (err)
res.send(err);
// embedded document updating
// http://mongoosejs.com/docs/2.7.x/docs/embedded-documents.html
modeltwo.modelone.push({
foo : req.body.foo,
bar.this : req.body.this,
bar.that : req.body.that
});
// save the modeltwo, and check for errors
modeltwo.save(function(err) {
if (err)
res.send(err);
res.json({ message: req.params.modeltwo_id + ' ' + req.body.foo });
});
});
});
To set the properties of bar in the model, you'll have to create the additional Object for it:
modeltwo.modelone.push({
foo : req.body.foo,
bar : {
this : req.body.this,
that : req.body.that
}
});
This is similar to how it was defined in the schema:
var OneModel = new Schema({
foo: String,
bar: {
this : String,
that : Number,
}
});

Removing a blog reference from a tag

I'm working on an application in Node with Mongoose where you're able to post blog entries and tag them. When a blog entry is deleted, I want to remove it's reference from the blog, and here's where I need help.
Below is the route for deleting a blog entry, but I get "TypeError: Cannot call method 'find' of undefined" when I try to delete a blog entry, so I guess my code below is wrong.
app.post('/blog/delete/:id', function(req, res){
model.BlogPost.findById(req.params.id, function (err, blog){
if (err) {
console.log(err);
// do something
}
blog.remove(function(err) {
console.log(err);
// do something
});
var query = model.Tag.find( { blogs: { $in : blog } } );
query.exec(function (err, tags) {
if (err) {
console.log(err);
// do something
}
tags.remove();
res.redirect('back');
});
});
});
Model for blog entries:
var BlogPostSchema = new Schema({
name : String,
type : String,
author : ObjectId,
title : String,
body : String,
buf : Buffer,
date: { type: Date, default: Date.now },
comments : [CommentSchema],
meta : {
upvotes : Number,
downvotes : Number,
// points : { type Number, default: },
favs : Number,
uniqueIPs : [String],
tags : [String]
}
});
modelObject.BlogPost = mongoose.model('BlogPost', BlogPostSchema);
Model for tags:
var TagSchema = new Schema({
name : String
, blogs : [String]
});
modelObject.TagSchema = TagSchema;
modelObject.Tag = mongoose.model('Tag', TagSchema);
Hard to tell with out line numbers, but looks like model.Tag may be undefined.
side note: you probably don't want to remove the tags unless the blog was found and removed successfully.

Mongoose - Retrieving object from ref query

I've got the following schemas:
var userSchema = new Schema({
firstName: String,
lastName: String,
emailAddress: {type: String, set: toLower, index: {unique: true}},
});
var eventMemberSchema = new Schema ({
user: { type : Schema.ObjectId, ref : 'User' },
created: { type: Date, default: Date.now }
});
var eventSchema = new Schema({
id : String,
name : String,
startDate : Date,
endDate : Date,
venue : { type : Schema.ObjectId, ref : 'Venue' },
invitees : [eventMemberSchema],
});
What I'm trying to do, is query the events, with an invitation._id, and ultimately get back the user...
invitees->eventMember->user
So far i've got:
Event
.find({ "invitees._id": req.query.invitation_id })
.populate('user')
.run(function (err, myEvent) {
console.log('error: ' + err);
console.log('event: '+ myEvent);
})
This works, and console shows the output of myEvent...
(I realise I don't need the populate part of my mongoose query above for this... i'm just testing)
I'm struggling on how to get, what I'd basically describe as: myEvent.invitees.user
EDIT
As an update...
This works - however, it kind of sucks, as now i'll need to do another db operation to get the user (i realise ref in mongoose does this under the hood)
Event
.findOne({ "invitees._id": "4f8eea01e2030fd11700006b"}, ['invitees.user'], function(err, evnt){
console.log('err: '+ err);
console.log('user id: '+ evnt.invitees[0].user); //this shows the correct user id
});
Try
Event
.find({ "invitees._id": req.query.invitation_id })
.populate('invitees.user')
Update:
Here is a working gist.

Resources