mongoose保存成功,但是数据库里没有数据,test数据库中没有Blog这个collection
发布于 8 年前 作者 favormm 3615 次浏览 来自 问答
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();
});
1 回复

blog.save();是个异步方法,加一个回调函数检查保存有没有错误

回到顶部