当我运行node.js服务器时,没有任何事情发生

时间:2017-07-19 20:38:26

标签: node.js mongodb mongoose

有没有人熟悉Node.js和mongoDB? 每当我运行服务器时,都没有任何反应。我应该看到console.log(“我们只是向数据库保存了一个猫”)

这是我app.js的代码:

var mongoose = require("mongoose");
mongoose.Promise = global.Promise;
mongoose.connect("mongodb://localhost/cat_app", {
  useMongoClient: true
});
var catSchema = new mongoose.Schema({
  name: String,
  age: Number,
  temperament: String
});
var Cat = mongoose.model("Cat", catSchema);
// Add a new cat to the DB
var george = new Cat({
  name: "George",
  age: 11,
  temperament: "Grouchy"
});
george.save(function(err, cat) {
  if (err) {
    console.log("SOMETHING WENT WRONG!")
  } else {
    console.log("WE JUST SAVED A CAT TO THE DB!")
    console.log(cat);
  }
});
// Retrieve all cats from the DB and console.log each one

那里有什么错误吗?

1 个答案:

答案 0 :(得分:0)

这应该有所帮助。

你通过bash或file启动mongod // mongo服务器。

然后启动mongo //连接到您的服务器

然后节点cats.js //在我的情况下它是southpark.js

代码内部像这样//这应该有用。

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/SP_app');


var spSchema = new mongoose.Schema({ 
    name: String,
    age: Number,
    temperament:String 
}); 


var SP = mongoose.model('SP', spSchema);

var eric = new SP({ 
    name:'Butters',
    age:10,
    temperament:'confused' 
});

eric.save(function(err, sp){ 
    if(err){  
        console.log("404 Something's Wrong") 
    }   else{ 
        console.log('WE JUST SAVED A CHARACTER TO THE DB:') 
        console.log(sp);  
    }
});