【问题标题】:Insert And Find Documents In mongoDB Using Node.js使用 Node.js 在 mongoDB 中插入和查找文档
【发布时间】:2022-10-06 14:52:42
【问题描述】:

我正在尝试使用带有 insertOne() 方法的 Node.js 将文档添加到 mongodb 集合,然后使用 .find() 获取所有集合,但我得到空字符串。我究竟做错了什么?

这是我的代码:

function connectToDB(cb) {
  MongoClient.connect(\'mongodb://localhost:27017/books\')
    .then((client) => {
      dbConnection = client.db()
      return cb()
    })
    .catch(err => {
      console.log(err)
      return cb(err)
    })
}

function getDB() {
  return dbConnection
}

function addDoc(db, doc) {
  db.collection(\'books\').insertOne(doc)
}

function returnCollection(db) {
  let books = []

  db.collection(\'books\').find({}).forEach(book => { books.push(book) });
  return books
}

connectToDB((err) => {
  if (!err) {
    db = getDB()
    const doc = {
    name: \'a\'
    }
    addDoc(db, doc)
    console.log(returnCollection(db))
  }
})

    标签: node.js mongodb


    【解决方案1】:

    尝试使用async await 处理异步代码:

    function connectToDB(cb) {
      MongoClient.connect('mongodb://localhost:27017/books')
        .then((client) => {
          dbConnection = client.db();
          return cb();
        })
        .catch((err) => {
          console.log(err);
          return cb(err);
        });
    }
    
    function getDB() {
      return dbConnection;
    }
    
    async function addDoc(db, doc) {
      await db.collection('books').insertOne(doc);
    }
    
    async function returnCollection(db) {
      return await db.collection('books').find({}).toArray();
    }
    
    connectToDB(async (err) => {
      if (!err) {
        db = getDB();
        const doc = {
          name: 'a',
        };
        await addDoc(db, doc);
        console.log(await returnCollection(db));
      }
    });
    

    【讨论】:

    • 为了使它成为一个数组,我需要在find({}) 之后添加.toArrsy()。谢谢!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-02
    • 2021-10-03
    • 2017-09-14
    • 1970-01-01
    • 2020-09-08
    • 1970-01-01
    • 2014-11-24
    相关资源
    最近更新 更多