我是新来的,我有一个问题,我希望你可以帮助我:)。
我的客户端有以下AJAX发送数据来更新数据库:
$.ajax({
type: 'PUT',
url: host + '/database',
data {
name: 'MisterX',
email: 'mister.x@gmail.com
},
sucess:function(sucess) {
alert('sucess');
},
err:function(err) {
console.log(err);
}
});
他们,在我的路线文件中我有:
app.put('/database', function(req, res) {
require('data', function (data){
var database = data;
database.save(function (err) {
if(err) {
console.log('err', err);
}
res.status(200).json('ok');
console.log('Database updated');
});
});
});
此put路线完全是理论上完成的,我不确切知道如何获取数据并在我的数据库中更新它们
我的架构:
var databaseSchema = mongoose.Schema({
name: String,
email: String,
});
如果有人可以给我指示,我很感激。
感谢。
答案 0 :(得分:0)
架构文件databaseScheme.js
....
var databaseSchema = mongoose.Schema({
nome: String,
email: String,
});
...
路线
/*
* body-parser is a piece of express middleware that
* reads a form's input and stores it as a javascript
* object accessible through `req.body`
*
* 'body-parser' must be installed (via `npm install --save body-parser`)
* For more info see: https://github.com/expressjs/body-parser
*/
var bodyParser = require('body-parser');
var app = express();
// instruct the app to use the `bodyParser()` middleware for all routes
app.use(bodyParser());
var Database = require(. / databaseScheme);
...
...
// As explained above, usage of 'body-parser' means
// that `req.body` will be filled in with the form elements
// Adds a new document
app.post('/database', function(req, res) {
var database = new Database();
database.name = request.body.name;
database.email = request.body.email;
database.save(function(err) {
if (err) {
console.log('err', err);
}
res.status(200).json('ok');
console.log('Database updated');
});
});
// Update a document
app.put('/database/:id', function(req, res) {
Database.findById(req.param('id'), function(err, database){
database.name = request.body.user;
database.email = request.body.user;
database.save(function(err) {
if (err) {
console.log('err', err);
}
res.status(200).json('ok');
console.log('Database updated');
});
});
});