我正在按照 MongoDB Atlas 博客教程将信息添加到 mongodb 中,但我收到了上述错误。我已尝试解决此错误,甚至尝试过但仍然遇到相同的问题...以下是我的连接文件
async function main(){
/**
* Connection URI. Update <username>, <password>, and <your-cluster-url> to reflect your cluster.
* See https://docs.mongodb.com/ecosystem/drivers/node/ for more details
*/
const uri = "mongodb+srv://an:abc@abc-2yzxs.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(uri);
try {
// Connect to the MongoDB cluster
await client.connect();
await createListing(client,
{
msg: client.msg
}
);
return client;
} catch (e) {
console.error(e);
} finally {
await client.close();
}
}
main().catch(console.error);
async function createListing(client, newListing){
const result = await client.db("mydb").collection("mycollection").insertOne(newListing);
console.log(`New listing created with the following id: ${result.insertedId}`);
}
以下是我的架构
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const mySchema = new Schema(
{
msg: {
type: String
}
}
);
let a = mongoose.model("mycollection", mySchema);
module.exports = a;
我的控制器:
const Log = require('../models/mySchema');
require('../connection');
function createListing(data){
let Log = new Log({ msg: data});
var err = Log.save();
console.log("err is : ", err)
}
exports.createListing = createListing;
这就是我从服务器文件调用的方式
let log = require('./controllers/myController');
log.createListing(data);
