Rumah > Soal Jawab > teks badan
var mongoose = require("mongoose"); // 连接字符串格式为mongodb://主机/数据库名 mongoose.connect('mongodb://localhost/test'); var Schema = mongoose.Schema; //骨架模版 var movieSchema = new Schema({ doctor : String, title : String, language : String, country : String, year : Number, summary : String, poster : String, flash : String }) //模型 var Movie = mongoose.model('Movie', movieSchema); //存储数据 var movie = new Movie({ title: '黑衣人三', doctor: '史密斯', year: 2018, flash: 'http://player.youku.com/player.php/sid/XNjA1Njc0NTUy/v.swf', country: '美国', language: '英语', summary: '好片' }) //保存数据库 movie.save(function(err) { if (err) { console.log('保存失败') return; } console.log('meow'); });
控制台出现下面的提示:
Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead:
http://mongoosejs.com/docs/promises.html
也没报错,但是数据就是插不进去
代言2016-11-09 15:49:17
1) 增加默认端口27017到主机地址。即 mongodb://localhost/test
改成 mongodb://localhost:27017/test
2) 用代码测试连接情况,确保连通。比如在mongoose.connect() 之后加这几句:
mongoose.connection.on('connected', function(){ console.log('Connection success!'); }); mongoose.connection.on('error', function(err){ console.log('Connection error: ' + err); }); mongoose.connection.on('disconnected', function(){ console.log('Connection disconnected'); });
3) 检查数据究竟存到了哪个collection里。我以前遇到的坑是,如果用你这句
var Movie = mongoose.model('Movie', movieSchema);
的写法,虽然你指定存入名叫 'Movie' 的collection,但可能实际存入的却是名为 'Movies' 的collection(Mongoose自动在后面加了个s)。很坑,但确实会发生。
在 Mongodb SHELL 里用 show collections 等命令,或者借助 RoboMongo, MongoBooster 这些可视化工具就能很容易检查出来。
三叔2016-11-09 15:48:35
把
mongoose.Promise = global.Promise;
加在
mongoose.connect('mongodb://localhost/test');
之前