mongoose 保存成功,但是用其它工具看 test 数据库中没有 Blog 这个 Collection

2016-06-01 14:36:15 +08:00
 CareiOS
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function (callback) {
  // yay!
  var blogSchema = new Schema({
    title:  String,
    author: String,
    body:   String,
    comments: [{ body: String, date: Date }],
    date: { type: Date, default: Date.now },
    hidden: Boolean,
    meta: {
      votes: Number,
      favs:  Number
    }
  });
  var Blog = mongoose.model('Blog', blogSchema);
  var blog = new Blog({
    title: 'this is my blog title',
    author: 'me',
    body: 'the body of my blog. can you see that?'
  });

  blog.save();
});

开发环境: Nodejs + Express + Mac + MongoDB, 都在最新版本

2688 次点击
所在节点    Node.js
10 条回复
DoraJDJ
2016-06-01 14:57:20 +08:00
用其他工具查的时候试试看 Blogs ?
GordianZ
2016-06-01 14:58:04 +08:00
.save 的返回你都没处理,你怎么知道保存成功了……
Mirachael
2016-06-01 15:10:25 +08:00
是 blogs 命名的 collection 吧,如果你要指定自定义的 collection, 需要在 schema 中设置,{collection: 'Blog'}
gyteng
2016-06-01 15:13:03 +08:00
其它工具是指 Robomongo 吗,旧版本的连接 mongodb 3.2 会有这个问题
CareiOS
2016-06-01 15:16:24 +08:00
@gyteng 对的,我是用的 Robomongo 0.8.4
CareiOS
2016-06-01 15:17:49 +08:00
@GordianZ 我在 save 中加了一个 function(error, model) {} ,error 为空, model 是有值的。
CareiOS
2016-06-01 15:22:15 +08:00
@mojixiang1102 我直接安装好 mongodb, 然后运行的 shell:mongod --dbpath ./data , 运行以上代码后,用 Robomongo 查看数据库 test 创建成功了,就是没有 Collections, test 数据库下面 Collections,Functions,Users 都为 0
CareiOS
2016-06-01 15:22:38 +08:00
@DoraJDJ 我试一试其他工具。
CareiOS
2016-06-01 15:28:03 +08:00
@DoraJDJ 果然是工具 Robomongo 问题。
doublelam
2016-06-01 17:17:05 +08:00
mongoose 会自动在集合名后加 s ,所以你的集合其实是 blogs ,如果要指定是 blog ,这样写:
var Blog = mongoose.model('Blog', blogSchema,'Blog');

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/282747

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX