获得“承诺{< pending> }"在"Log.save();"处出现错误-Mongodb [英] Getting "Promise { <pending> }" error at "Log.save();" - Mongodb

查看:59
本文介绍了获得“承诺{< pending> }"在"Log.save();"处出现错误-Mongodb的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在关注MongoDB Atlas博客教程,以将信息添加到mongodb中,但出现上述错误.我尝试解决此错误,甚至尝试解决此错误,但仍然遇到相同的问题... 以下是我的连接文件

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}`);
}

以下是我的模式

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;


这就是我从服务器文件中调用的方式

this is how I'm calling from server file

let log = require('./controllers/myController');

log.createListing(data);

推荐答案

我个人不会使用猫鼬,尽管您的教程会使用猫鼬.我只是使用mongodb.

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' })
}

我知道这与您遇到的问题不同,但是我不知道为什么需要mongoose.不是真的.

I know it's different from the problem you have but I just don't know why mongoose is needed. It's not really.

这篇关于获得“承诺{&lt; pending&gt; }"在"Log.save();"处出现错误-Mongodb的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆