Skip to content

Instantly share code, notes, and snippets.

@frontconnect
Created September 28, 2012 08:22
Show Gist options
  • Save frontconnect/3798625 to your computer and use it in GitHub Desktop.
Save frontconnect/3798625 to your computer and use it in GitHub Desktop.
node.js - mongoose - while sending a data from client to server with ajax-post request
Hi,
I'm trying to send a mongodb schema from client to the server. I put the server (server.js) and client (client.js) codes above. When I press the button on the client side, I log the incoming data into the console.
In the console output what I have is:
{
field1: `container field`,
subSchema: []
}
However, what I expect to have is:
{
field1: `myfield`,
subSchema: { field1:`sub field1`, field2: `sub field2` }
}
Why can't I get the exptected result? Do you have any comment?
Thanks in regard...
var subSchema1 = {
field1: "sub field1",
field2: "sub field2"
};
var container1 = {
field1: "container field",
subSchema: subSchema1
};
$(document).ready(function() {
$('button').button();
$('button').click(function() {
$.ajax({type: 'POST',
url: "/send",
data: container1, // here I send the data when the button on the browser is clicked.
dataType: "json"
}).done(function( msg ) {
console.log( "Data Saved: " + msg );
}).fail(function(msg){
console.log("Fail! " +msg.data);
});
});
});
//create express web framework
var express = require('express');
var app = express();
var util = require('util');
app.use(express.static(process.cwd() + "/public"));
app.use(express.bodyParser());
app.listen(9000);
var mongoose = require('mongoose');
var db = mongoose.createConnection('localhost', 'deneme');
var subfieldSchema = mongoose.Schema({
field1: 'string',
field2: 'string'
});
var subfieldSch = db.model('subfieldSchema', subfieldSchema);
var containerSchema = mongoose.Schema({
field1: 'string',
subSchema: [subSchema]
});
var containerSch = db.model('tag', tagSchema);
app.post('/send', function(req,res){
if (req.body ){
var newVal = new Route({
field1: req.body.field1,
subSchema: req.body.subSchema
});
util.log(newVal);
newVal.save(function(err){
res.end("Err: Send ended!");
});
res.send({status: "ok", message: "Received."});
}else{
res.send({status: "nok", message: "Nothing received."});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment