admin管理员组文章数量:1025512
As part of my course, I'm learning MongoDB and now Mongoose. I've written the code exactly as done in the lesson, but when trying to start it with node app.js
, I get the following error:
node app.js
Output:
(node:25772) ` **UnhandledPromiseRejectionWarning: MongoNotConnectedError: MongoClient must be connected to perform this operation**
`at Object.getTopology (C:\Users\donal\OneDrive\Desktop\Udemy Web Development\FruitsProject\node_modules\mongoose\node_modules\mongodb\lib\utils.js:391:11)
at Collection.insertOne (C:\Users\donal\OneDrive\Desktop\Udemy Web Development\FruitsProject\node_modules\mongoose\node_modules\mongodb\lib\collection.js:150:61)
at NativeCollection.<puted> [as insertOne] (C:\Users\donal\OneDrive\Desktop\Udemy Web Development\FruitsProject\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:200:33)
at NativeCollection.Collection.doQueue (C:\Users\donal\OneDrive\Desktop\Udemy Web Development\FruitsProject\node_modules\mongoose\lib\collection.js:135:23)
at C:\Users\donal\OneDrive\Desktop\Udemy Web Development\FruitsProject\node_modules\mongoose\lib\collection.js:82:24
at processTicksAndRejections (internal/process/task_queues.js:77:11)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:25772) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see .html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:25772) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
I have mongosh running in a separate tab in the terminal, and I've tried several searches to look for similar problems. How can I fix it?
Here's my app.js code in full:
const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost:27017/fruitsDB");
const fruitSchema = new mongoose.Schema({
name: String,
rating: Number,
review: String
});
const Fruit = mongoose.model("Fruit", fruitSchema);
const fruit = new Fruit({
name: "Apple",
rating: 7,
review: "Pretty solid as a fruit"
});
fruit.save();
mongoose.connection.close();
const findDocuments = function(db, callback) {
const collection = db.collection('fruits');
collection.find({}).toArray(function(err, fruits) {
assert.equal(err, null);
console.log("Found the following records");
console.log(fruits)
callback(fruits);
});
}
As part of my course, I'm learning MongoDB and now Mongoose. I've written the code exactly as done in the lesson, but when trying to start it with node app.js
, I get the following error:
node app.js
Output:
(node:25772) ` **UnhandledPromiseRejectionWarning: MongoNotConnectedError: MongoClient must be connected to perform this operation**
`at Object.getTopology (C:\Users\donal\OneDrive\Desktop\Udemy Web Development\FruitsProject\node_modules\mongoose\node_modules\mongodb\lib\utils.js:391:11)
at Collection.insertOne (C:\Users\donal\OneDrive\Desktop\Udemy Web Development\FruitsProject\node_modules\mongoose\node_modules\mongodb\lib\collection.js:150:61)
at NativeCollection.<puted> [as insertOne] (C:\Users\donal\OneDrive\Desktop\Udemy Web Development\FruitsProject\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:200:33)
at NativeCollection.Collection.doQueue (C:\Users\donal\OneDrive\Desktop\Udemy Web Development\FruitsProject\node_modules\mongoose\lib\collection.js:135:23)
at C:\Users\donal\OneDrive\Desktop\Udemy Web Development\FruitsProject\node_modules\mongoose\lib\collection.js:82:24
at processTicksAndRejections (internal/process/task_queues.js:77:11)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:25772) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:25772) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
I have mongosh running in a separate tab in the terminal, and I've tried several searches to look for similar problems. How can I fix it?
Here's my app.js code in full:
const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost:27017/fruitsDB");
const fruitSchema = new mongoose.Schema({
name: String,
rating: Number,
review: String
});
const Fruit = mongoose.model("Fruit", fruitSchema);
const fruit = new Fruit({
name: "Apple",
rating: 7,
review: "Pretty solid as a fruit"
});
fruit.save();
mongoose.connection.close();
const findDocuments = function(db, callback) {
const collection = db.collection('fruits');
collection.find({}).toArray(function(err, fruits) {
assert.equal(err, null);
console.log("Found the following records");
console.log(fruits)
callback(fruits);
});
}
Share
Improve this question
edited Aug 17, 2023 at 20:07
Peter Mortensen
31.6k22 gold badges110 silver badges133 bronze badges
asked Oct 11, 2021 at 10:58
DonaldDonald
451 silver badge6 bronze badges
2 Answers
Reset to default 3I ran into the same issue and the culprit was calling mongoose.connection.close();
in the body of your JavaScript code. as AnanthDev mentioned, mongoose is asynchronous and ends up closing the connection before it's able to perform the actions.
The following works because mongoose.connection.close()
is in a callback function and does not run until after the actions is performed.
Fruit.insertMany([kiwi, orange, banana], function(err) {
if (err) {
console.log(err);
} else {
mongoose.connection.close();
console.log("Successfully saved all the fruits to fruitsDB");
}
})
mongoose.connect
is async, so you're trying to execute the code before a connection is established with the database.
const connectToMongo = async() => {
await mongoose.connect("mongodb://localhost:27017/fruitsDB", {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
});
return mongoose;
};
You can now use async/await or .then() to wait till a connection is established
(async function () {
await connecToMongo();
const fruitSchema = new mongoose.Schema({
name: String,
rating: Number,
review: String
});
const Fruit = mongoose.model("Fruit", fruitSchema);
const fruit = new Fruit({
name: "Apple",
rating: 7,
review: "Pretty solid as a fruit"
});
fruit.save();
mongoose.connection.close();
const findDocuments = function (db, callback) {
const collection = db.collection('fruits');
collection.find({}).toArray(function (err, fruits) {
assert.equal(err, null);
console.log("Found the following records");
console.log(fruits)
callback(fruits);
});
}
})
As part of my course, I'm learning MongoDB and now Mongoose. I've written the code exactly as done in the lesson, but when trying to start it with node app.js
, I get the following error:
node app.js
Output:
(node:25772) ` **UnhandledPromiseRejectionWarning: MongoNotConnectedError: MongoClient must be connected to perform this operation**
`at Object.getTopology (C:\Users\donal\OneDrive\Desktop\Udemy Web Development\FruitsProject\node_modules\mongoose\node_modules\mongodb\lib\utils.js:391:11)
at Collection.insertOne (C:\Users\donal\OneDrive\Desktop\Udemy Web Development\FruitsProject\node_modules\mongoose\node_modules\mongodb\lib\collection.js:150:61)
at NativeCollection.<puted> [as insertOne] (C:\Users\donal\OneDrive\Desktop\Udemy Web Development\FruitsProject\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:200:33)
at NativeCollection.Collection.doQueue (C:\Users\donal\OneDrive\Desktop\Udemy Web Development\FruitsProject\node_modules\mongoose\lib\collection.js:135:23)
at C:\Users\donal\OneDrive\Desktop\Udemy Web Development\FruitsProject\node_modules\mongoose\lib\collection.js:82:24
at processTicksAndRejections (internal/process/task_queues.js:77:11)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:25772) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see .html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:25772) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
I have mongosh running in a separate tab in the terminal, and I've tried several searches to look for similar problems. How can I fix it?
Here's my app.js code in full:
const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost:27017/fruitsDB");
const fruitSchema = new mongoose.Schema({
name: String,
rating: Number,
review: String
});
const Fruit = mongoose.model("Fruit", fruitSchema);
const fruit = new Fruit({
name: "Apple",
rating: 7,
review: "Pretty solid as a fruit"
});
fruit.save();
mongoose.connection.close();
const findDocuments = function(db, callback) {
const collection = db.collection('fruits');
collection.find({}).toArray(function(err, fruits) {
assert.equal(err, null);
console.log("Found the following records");
console.log(fruits)
callback(fruits);
});
}
As part of my course, I'm learning MongoDB and now Mongoose. I've written the code exactly as done in the lesson, but when trying to start it with node app.js
, I get the following error:
node app.js
Output:
(node:25772) ` **UnhandledPromiseRejectionWarning: MongoNotConnectedError: MongoClient must be connected to perform this operation**
`at Object.getTopology (C:\Users\donal\OneDrive\Desktop\Udemy Web Development\FruitsProject\node_modules\mongoose\node_modules\mongodb\lib\utils.js:391:11)
at Collection.insertOne (C:\Users\donal\OneDrive\Desktop\Udemy Web Development\FruitsProject\node_modules\mongoose\node_modules\mongodb\lib\collection.js:150:61)
at NativeCollection.<puted> [as insertOne] (C:\Users\donal\OneDrive\Desktop\Udemy Web Development\FruitsProject\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:200:33)
at NativeCollection.Collection.doQueue (C:\Users\donal\OneDrive\Desktop\Udemy Web Development\FruitsProject\node_modules\mongoose\lib\collection.js:135:23)
at C:\Users\donal\OneDrive\Desktop\Udemy Web Development\FruitsProject\node_modules\mongoose\lib\collection.js:82:24
at processTicksAndRejections (internal/process/task_queues.js:77:11)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:25772) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:25772) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
I have mongosh running in a separate tab in the terminal, and I've tried several searches to look for similar problems. How can I fix it?
Here's my app.js code in full:
const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost:27017/fruitsDB");
const fruitSchema = new mongoose.Schema({
name: String,
rating: Number,
review: String
});
const Fruit = mongoose.model("Fruit", fruitSchema);
const fruit = new Fruit({
name: "Apple",
rating: 7,
review: "Pretty solid as a fruit"
});
fruit.save();
mongoose.connection.close();
const findDocuments = function(db, callback) {
const collection = db.collection('fruits');
collection.find({}).toArray(function(err, fruits) {
assert.equal(err, null);
console.log("Found the following records");
console.log(fruits)
callback(fruits);
});
}
Share
Improve this question
edited Aug 17, 2023 at 20:07
Peter Mortensen
31.6k22 gold badges110 silver badges133 bronze badges
asked Oct 11, 2021 at 10:58
DonaldDonald
451 silver badge6 bronze badges
2 Answers
Reset to default 3I ran into the same issue and the culprit was calling mongoose.connection.close();
in the body of your JavaScript code. as AnanthDev mentioned, mongoose is asynchronous and ends up closing the connection before it's able to perform the actions.
The following works because mongoose.connection.close()
is in a callback function and does not run until after the actions is performed.
Fruit.insertMany([kiwi, orange, banana], function(err) {
if (err) {
console.log(err);
} else {
mongoose.connection.close();
console.log("Successfully saved all the fruits to fruitsDB");
}
})
mongoose.connect
is async, so you're trying to execute the code before a connection is established with the database.
const connectToMongo = async() => {
await mongoose.connect("mongodb://localhost:27017/fruitsDB", {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
});
return mongoose;
};
You can now use async/await or .then() to wait till a connection is established
(async function () {
await connecToMongo();
const fruitSchema = new mongoose.Schema({
name: String,
rating: Number,
review: String
});
const Fruit = mongoose.model("Fruit", fruitSchema);
const fruit = new Fruit({
name: "Apple",
rating: 7,
review: "Pretty solid as a fruit"
});
fruit.save();
mongoose.connection.close();
const findDocuments = function (db, callback) {
const collection = db.collection('fruits');
collection.find({}).toArray(function (err, fruits) {
assert.equal(err, null);
console.log("Found the following records");
console.log(fruits)
callback(fruits);
});
}
})
本文标签: javascriptMongoClient not connected error while trying to use MongooseStack Overflow
版权声明:本文标题:javascript - MongoClient: not connected error while trying to use Mongoose - Stack Overflow 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://it.en369.cn/questions/1745633346a2160295.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论