项目场景:
提示:最新版的MongoDB V7.0.1 + nodejsV18数据库操作
问题描述
提示:无论 mongoose 和 mongodb 均不能有效操作数据库,提示错误:
1、MongooseServerSelectionError: connect ECONNREFUSED ::1:27017
at connectionFailureError (C:\program files\nodejs\node_global\node_modules\mongoose\node_modules\.store\mongodb@5.8.1\node_modules\mongodb\lib\cmap\connect.js:367:20)
at Socket.<anonymous> (C:\program files\nodejs\node_global\node_modules\mongoose\node_modules\.store\mongodb@5.8.1\node_modules\mongodb\lib\cmap\connect.js:290:22)
at Object.onceWrapper (node:events:629:26)
at Socket.emit (node:events:514:28)
at emitErrorNT (node:internal/streams/destroy:151:8)
at emitErrorCloseNT (node:internal/streams/destroy:116:3)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
cause: Error: connect ECONNREFUSED ::1:27017
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1495:16) {
errno: -4078,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '::1',
port: 27017
},
[Symbol(errorLabels)]: Set(1) { 'ResetPool' }
},
2、MongooseError: Query.prototype.exec() no longer accepts a callback
at model.Query.exec (C:\Program Files\nodejs\node_global\node_modules\mongoose\lib\query.js:4380:11)
at Object.<anonymous> (E:\work2023\projects\www\connMDB.js:38:34)
at Module._compile (node:internal/modules/cjs/loader:1256:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1310:10)
at Module.load (node:internal/modules/cjs/loader:1119:32)
at Module._load (node:internal/modules/cjs/loader:960:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:23:47
虽然connect 成功,但不能获取正确数据
原因分析:
提示:版本问题
解决方案:
提示:Find a Document
import { MongoClient } from "mongodb";
// Replace the uri string with your MongoDB deployment's connection string.
const uri = "<connection string uri>";
const client = new MongoClient(uri);
async function run() {
try {
// Get the database and collection on which to run the operation
const database = client.db("sample_mflix");
const movies = database.collection("movies");
// Query for a movie that has the title 'The Room'
const query = { title: "The Room" };
const options = {
// Sort matched documents in descending order by rating
sort: { "imdb.rating": -1 },
// Include only the `title` and `imdb` fields in the returned document
projection: { _id: 0, title: 1, imdb: 1 },
};
// Execute query
const movie = await movies.findOne(query, options);
// Print the document returned by findOne()
console.log(movie);
} finally {
await client.close();
}
}
run().catch(console.dir);