I have some trouble saving a object I made in Express nodejs using mongoose.
It always says its saved but can never find the object even if i log into the server and try to get it myself.
Express route to save mongodb:
router.post('/share', function(req, res, next){
//console.log('Post Request Made', req);
//switch to be inputed as parameters of the request
//save share
var share = new Shares({ link: req.body.link, description: req.body.description });
// var share = new Shares({ req.data.link, req.data.description });
console.log('request body', req.body);
console.log('to be added', share);
//save to database
share.save(function(err, share){
if(err){
console.log(err);
} else {
console.log('the object was saved' , share);
var id = share._id;
res.send(id);
}
});
});
Console log:
request body { link: 'test', description: 'test' }
to be added { link: 'test',
description: 'test',
_id: 5840b0393181d4000f652cba,
clicks: 0 }
the object was saved { __v: 0,
link: 'test',
description: 'test',
_id: 5840b0393181d4000f652cba,
clicks: 0 }
POST /share 200 73.618 ms - 26
This is the link page with id: 5840b0393181d4000f652cba
found []
GET /fluff/link/5840b0393181d4000f652cba 200 20.387 ms - 266
Configuration:
var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://mongo/shares');
require('./models/Shares');
Solved the problem. My problem was that I'm a noob in mongo
shell and mongodb in general.
I was actually saving properly, but the way I was searching in the mongo
shell was wrong. I didn't realize every time your in the mongo
shell it starts in the test
database if you run mongo
with no arguments.
So first thing is to enter the database that you want to be in:
`mongo [database_name]`
then check for any documents in there by:
`db.collections.count()`
`db.collections.find()`
My real problem was that my Shares.findById()
was wrong and I had to look up the proper parameters.
this is what the working version looks like now:
Shares.findById(id.toString(), function(err, share){
if(err){
console.log('error', err);
} else {
console.log('found', share);
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.