2017-04-16 91 views
0

OS是Os X.我通过brew安装了mongodb。Mongodb不通过express.js保存

我打开终端,并进入

mongod 

然后几排被印刷在终端中。数据库似乎绝对正常运行。我参见例如:

db version v3.4.3 
waiting for connections on port 27017 

我然后打开另一个端子和输入

mongo 

我看到然后:

MongoDB shell version v3.4.3 
connecting to: mongodb://127.0.0.1:27017 
MongoDB server version: 3.4.3   

我则在该终端

show dbs 

键入我看到:

admin 0.000GB 
api 0.000GB 
local 0.000GB 

所以我进入

use api 
db.movie.find(); 

终端打印:

{ "_id" : ObjectId("58f34b96d7eac221145a5d4e"), "name" : "tutorials point" } 
{ "_id" : ObjectId("58f367e198554c65c4a34c9f"), "name" : "lalaland" }  

我进入:

db.movie.insert({ name: "forreste gump"}); 

,然后查找()命令返回:

{ "_id" : ObjectId("58f34b96d7eac221145a5d4e"), "name" : "tutorials point" } 
{ "_id" : ObjectId("58f367e198554c65c4a34c9f"), "name" : "lalaland" } 
{ "_id" : ObjectId("58f369259a667b015582e4b8"), "name" : "forreste gump" } 

现在,我用express.js创建一个新的节点应用程序。这是代码:

var express = require('express'); 
var app  = express(); 
var mongoose = require('mongoose'); 
mongoose.Promise = global.Promise; 
var connection = mongoose.createConnection('mongodb://localhost/api'); 

connection.on('open', function() { 
    console.log('opened'); 
}); 

var movieSchema = mongoose.Schema({ 
    name: String 
}); 

var Movie = mongoose.model('Movie', movieSchema); 
var pulp = new Movie({ name: 'pulp fiction' }); 
pulp.save(function (err, fluffy) { 
    if (err){ 
     console.error("Error:"); 
     console.error(err); 
    } 
    console.error('inside save'); 
}); 
console.log('pulp.name'); 
console.log(pulp.name); 

在的package.json我进入

"mongoose": "~4.9.4", 

,然后再运行安装NPM(我可以看到该版本已安装)

所以,当我开始应用程式

node app.js 

在终端我看到

pulp.name 
pulp fiction 
opened  

这意味着“pulp.save”行永远不会被执行。或者,可能是由于某些没有出现的错误而停止。我在这变得疯狂。我真的不知道问题是什么。 mongod启动并运行,我用猫鼬连接到正确的数据库。但仍然无法保存文件,最重要的是,我没有看到任何错误。这显然必须发生在某个地方。 如何深入调试猫鼬操作?

PS:当我去的地方,我跑蒙戈客户终端和I型:

db.movie.find() 

我只看到

{ "_id" : ObjectId("58f34b96d7eac221145a5d4e"), "name" : "tutorials point" } 
{ "_id" : ObjectId("58f367e198554c65c4a34c9f"), "name" : "lalaland" } 
{ "_id" : ObjectId("58f369259a667b015582e4b8"), "name" : "forreste gump" } 

因此, “低俗小说” 从未被添加。

+0

'电影'vs'电影'也许? – Ties

+0

mongo client with db.Movie.find(); – oderfla

+0

使用正确的数据库? – Ties

回答

1

不同的是mongoose.connect() VS mongoose.createConnection()(另见this question

基本工作原理如下: 使用mongoose.createConnection()你要做的:

var db = mongoose.createConnection(...) 
// And use the db variable 
var Model = db.model(...); // etc... 

而不是使用mongoose.model(...)

这是因为通过使用mongoose.createConnection()您不在mongoose对象上创建连接,只在db对象的范围内。