将应用程序连接到mongodb

时间:2020-01-21 21:49:38

标签: node.js mongodb mongoose

我有通过终端在vsc中运行的Mongodb。我已经下载了猫鼬。当我尝试运行该应用程序时,没有任何反应。我已经在连接字符串中尝试了localhost,我已经尝试了localhost:27017,我根本无法响应以了解它是否已连接。我还下载了npm mongodb软件包,以防万一。

var mongoose = require ("mongoose")

mongoose.connect("mongodb://127.0.0.1:27017/cat_app", {useNewUrlParser: true});

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

var Cat = mongoose.model("Cat", catSchema);

var george = new Cat ({
    name: "George",
    age: 11,
    temperment: "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)}})

2 个答案:

答案 0 :(得分:0)

为了更好的可读性,我对您的代码进行了一些重构,并在我的机器上进行了尝试。通过运行命令“ node app.js”,代码成功将条目插入了数据库。请尝试以下代码,如果对您不起作用,则可能是您的mongo配置有问题。

var mongoose = require("mongoose");

mongoose.connect("mongodb://127.0.0.1:27017/cat_app", {useNewUrlParser: true});

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

var Cat = mongoose.model("Cat", catSchema);

var george = new Cat ({
    name: "George",
    age: 11,
    temperment: "Grouchy"
});

george.save((err, cat) => {
        if (err) {
            console.log("Something Went Wrong");
        } else {
            console.log("We Just Saved A Cat To The DB"); 
            console.log(cat);
        }
    }
);

答案 1 :(得分:0)

您需要等到猫鼬使用Promise或回调函数连接到DB之前:

var mongoose = require ("mongoose")


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

var Cat = mongoose.model("Cat", catSchema);

mongoose.connect("mongodb://127.0.0.1:27017/cat_app", {useNewUrlParser: true}, function (err) {
  if (err) {
    console.error(err);
    return;
  }

  var george = new Cat({
    name: "George",
    age: 11,
    temperment: "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);
    }
  })
});

这也是检查任何连接错误的好机会