简体   繁体   English

为什么这个node.js + mongoose代码没有保存到DB?

[英]Why doesn't this node.js + mongoose code save to the DB?

I'm learning Node.js + mongodb using a simple tutorial - the problem is that I can't get it to save(). 我正在使用一个简单的教程学习Node.js + mongodb - 问题是我无法得到它来保存()。

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? 有任何想法吗?

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. 事实证明我的mongodb服务器没有运行,因为我在ubuntu中安装mongo时默认没有安装/ data / db目录。 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. 我创建了一个名为validate()的模式方法,它干扰了MongoDB的validate()函数,这就是为什么它没有保存到数据库并且给我零错误。 So don't name a method in your schema entitled validate(). 因此,不要在名为validate()的模式中命名方法。 Hopefully my dumbness will save you a lot of time. 希望我的愚蠢能为你节省很多时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM