Reputation: 129
When I execute this function from something like Postman:
router.get('/db', function(req, res, next) {
tune.find({}, function (err, results) {
res.json(results);
});
});
My database returns this:
[{"_id":"56f30425ba97bb301fe6ab1a","__v":0},
{"_id":"56f30514f9b7ea3b1f1fd9f7","__v":0},
{"_id":"56f306bb9c8203451f2cc58a","__v":0},
{"_id":"56f306ca9c8203451f2cc58b","__v":0},
{"_id":"56f306e99c8203451f2cc58c","__v":0},
{"_id":"56f33d43b64d540b208b6c3c","__v":0}]
My mongoose schema:
var Schema = mongoose.Schema;
var track = new Schema({
title: String,
artist: String,
genre: String
});
var tune = mongoose.model('tune', track);
My post:
router.post('/db', function(req, res, next) {
var tune1 = new tune(req.body);
tune1.save(function (err) {
if (err) { console.log('error!');}
else {
res.json({message: 'Track successfully posted'});
}
});
});
Request Post:
app.use('/users', userRoutes);
var options = { method: 'POST',
url: 'http://localhost:3000/users/db',
headers:
{ 'content-type': 'application/x-www-form-urlencoded',
'postman-token': '',
'cache-control': 'no-cache' },
form: { title: '000000', artist: 'blah blah', genre: 'rap' } };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
When I do a post command from Postman I get a successful post message. Is it just the way I am returning the JSON? I want to be able to see title, artist, and genre for every post in the DB.
Thanks
Upvotes: 1
Views: 129
Reputation: 745
In this instance, Mongoose simply isn't saving what you're expecting. Try taking a look at req.body
and tune1
in a debugger to make sure you're getting the expected result.
It might also help to set strict
to 'throw'
in your schema, just so we get an error back when we attempt to save an invalid tune
:
var track = new Schema({
title: String,
artist: String,
genre: String
}, {
strict: 'throw'
});
Upvotes: 1