我拥有的代码:
const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost:27017/sandbox");
const db = mongoose.connection;
db.on("error", err => {
console.error("conection error", err);
});
db.once("Open", () => {
console.log("Connection Successful");
// all database communication goes here
const Schema = mongoose.Schema;
const AnimalSchema = new Schema({
type: String,
size: String,
color: String,
mass: Number,
name: String
});
let Animal = mongoose.model("Animal", AnimalSchema);
const elephant = new Animal({
type: "elephant",
size: "big",
color: "grey",
mass: 6000,
name: "eleanor"
});
elephant.save(err => {
if (err) {
console.log("Save Failed");
} else {
console.log("Saved!");
}
db.close(() => {
console.log("Connection Closed!");
});
});
});
当我在后台运行mongodb时运行此代码 (mongod在一个终端窗口中运行,而mongo在另一个终端窗口中运行)我在控制台中看不到任何指示应用程序正在运行的信息(在代码中应该发生日志,例如:连接成功)
在运行mongo的终端中我确实看到了这一点,并且每次我运行该应用程序时它都会增加。
I NETWORK [listener] connection accepted from 127.0.0.1:57449 #2 (2 connections now open)
答案 0 :(得分:0)
尝试启用,而不是立即使用。
从未使用过一次事件
db.on("open", () => {
console.log("Connection Successful");
});