问题
I am following MongoDB Atlas Blog tutorial to add info into mongodb but I am getting the above mentioned error. I have tried to resolve this error, even tried to then but still getting the same issue... Following is my connection file
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}`);
}
and following is my schema
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const mySchema = new Schema(
{
msg: {
type: String
}
}
);
let a = mongoose.model("mycollection", mySchema);
module.exports = a;
My Controller:
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;
this is how I'm calling from server file
let log = require('./controllers/myController');
log.createListing(data);
回答1:
Personally I wouldn't use mongoose, although you tutorial does. I just use mongodb
.
import { connect } from 'mongodb'
async function main() {
// try-catch
const MONGO = 'mongodb+srv://an:abc@abc-2yzxs.mongodb.net/testretryWrites=true&w=majority'
const client = await connect(MONGO, {
useNewUrlParser: true,
useUnifiedTopology: true })
const mongo = client.db()
const Log = mongo.collection('Log')
await Log.insertOne({ message: 'test' })
}
I know it's different from the problem you have but I just don't know why mongoose
is needed. It's not really.
回答2:
you need to use await before Log.save()
to log actual value returning by the function instead of promise pending
you are getting.
async function createListing(data){
let Log = new Log({ msg: data});
let err = await Log.save();
console.log("err is : ", err)
}
来源:https://stackoverflow.com/questions/60523815/getting-promise-pending-error-at-log-save-mongodb