I'm learning Node.js + mongodb using a simple tutorial - the problem is that I can't get it to save().
This is the code I'm running:
mongoose = require('mongoose'),
Schema = mongoose.Schema;
PostSchema = new Schema({
title: String,
body: String,
date: Date
});
mongoose.connect('mongodb://localhost/posterdb');
mongoose.model('Post', PostSchema);
var Post = mongoose.model('Post');
// create a post and save it
var post = new Post();
post.title = 'My first post';
post.body = 'Post body';
post.date = Date.now();
post.save(function(err) {
console.log('error check');
if(err) { throw err; }
console.log('saved');
mongoose.disconnect();
});
It doesn't print anything on the console. Any ideas?
I'm learning Node.js + mongodb using a simple tutorial - the problem is that I can't get it to save().
This is the code I'm running:
mongoose = require('mongoose'),
Schema = mongoose.Schema;
PostSchema = new Schema({
title: String,
body: String,
date: Date
});
mongoose.connect('mongodb://localhost/posterdb');
mongoose.model('Post', PostSchema);
var Post = mongoose.model('Post');
// create a post and save it
var post = new Post();
post.title = 'My first post';
post.body = 'Post body';
post.date = Date.now();
post.save(function(err) {
console.log('error check');
if(err) { throw err; }
console.log('saved');
mongoose.disconnect();
});
It doesn't print anything on the console. Any ideas?
javascript
mongodb
node.js
mongoose
Share
asked Dec 7, 2011 at 8:00
Bee SanBee San2,67522 gold badges2121 silver badges2020 bronze badges4
1Does the connection get established? Try the event mongoose.connection.on("open", function() { ... }).
– pimvdb
CommentedDec 7, 2011 at 8:08
Hmm, interesting. It doesn't get established. mongoose.connect('mongodb://localhost/posterdb', function(err){ console.log(err); }); Prints : { stack: [Getter/Setter], arguments: undefined, type: undefined, message: 'failed to connect to [localhost:27017]' }
– Bee San
CommentedDec 7, 2011 at 8:14
1Are you sure the server is running at that host and port?
– pimvdb
CommentedDec 7, 2011 at 8:19
Indeed, the server wasn't running. Had no data directory by default. Thanks!
– Bee San
CommentedDec 7, 2011 at 8:28
Add a ment
|
2 Answers
2
Reset to default
4
Turns out my mongodb server wasn't running because I didn't have a /data/db directory installed by default upon installing mongo in ubuntu. Created that, started the server, everything worked fine. Solved.
If anyone found this question for the same reason I did, then maybe this will help:
Found that I couldn't save a new object to my collection. I had made a schema method named validate() which interfered with MongoDB's validate() function, so that's why it wasn't saving to the DB and was giving me zero errors. So don't name a method in your schema entitled validate(). Hopefully my dumbness will save you a lot of time.