简体   繁体   English

节点JS MongoDB collection.find.toArray不返回任何值

[英]Node JS MongoDB collection.find.toArray returns no value

I'm building a website that lets people write sticky notes and print it to them on the screen. 我正在建立一个网站,使人们可以书写便签并将其打印在屏幕上。 I want to store the sticky notes inside a mongoDB with a db called stickyNotes and a collection called stickyNotes which currently has two documents. 我想将粘滞便笺存储在mongoDB中,该数据库具有一个名为stickyNotes的数据库和一个名为stickyNotes的集合,该集合当前有两个文档。

I have a variable called stickyNotes which suppose to get the documents from the stickyNotes collection on the db but when I use the collection.find.toArray from the mongodb library to enter the documents to the stickyNotes variable in an asynchronous way, it shows an empty array value. 我有一个名为stickyNotes的变量,它想从数据库上的stickyNotes集合中获取文档,但是当我使用mongodb库中的collection.find.toArray以异步方式将文档输入到stickyNotes变量时,它显示为空数组值。

This is my server.js file: 这是我的server.js文件:

const express = require("express");
const mongo = require("mongodb").MongoClient;
const app = express();

let stickyNotes = [];

//mongodb get all sticky notes
const mongoUrl = "mongodb://localhost:27017";
mongo.connect(mongoUrl, { useNewUrlParser: true }, async function(
  err,
  connection
) {
  if (err) {
    console.error(err);
  } else {
    console.log("Succesfully connected to the database");
    const db = connection.db("stickyNotes");
    const stickyNotesCollection = db.collection("stickyNotes");
    stickyNotes = await stickyNotesCollection.find({}).toArray();
  }
  connection.close();
});

console.log(stickyNotes);

app.use(express.static("./src/public"));

app.get("/sticky-notes", (req, res) => {
  console.log("Got a request for sticky notes");
  res.json(stickyNotes);
});

const port = 3000;
app.listen(port, () => {
  console.log(`App is running on port ${port}`);
});

Can try with: 可以尝试:

stickyNotesCollection.find({}, (err, result) => {
    if (err) throw err;
    stickyNotes = result;
  });

or find result in array: 或在数组中查找结果:

collection.find().toArray(function(err, result) {
    console.log(result);
});

or iterate: 或迭代:

collection.find().each(function(err, result) {
    //once result
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM