简体   繁体   English

变量 scope 错误时尝试 JSON.stringify object 在存储所述 ZA8CFDE6331BD59EB2AC96F891ZB4 之后

[英]Variable scope error when attempting to JSON.stringify object after storing said object in Mongo DB

Firstly, I would like to address my situation.首先,我想谈谈我的情况。 I am attempting to build a to-do list webapp, in which I save my tasks in a MongoDB, so that I can pull the tasks from the MongoDB so that on the front end the task remains there permanently.我正在尝试构建一个待办事项列表 webapp,其中我将我的任务保存在 MongoDB 中,以便我可以从 MongoDB 中提取任务,以便在前端永久保留任务。 The problem is, when I try to convert the object containing the task into a string, so that I can reference it in my client side JS, I get variable scope error (I am assuming) where the object is undefined, and thus I cannot res.end the data to my script.js file.问题是,当我尝试将包含任务的 object 转换为字符串,以便我可以在客户端 JS 中引用它时,我得到变量 scope 错误(我假设)其中 ZA8CFDE6331BD59EB2AC96F8911C4B 无法定义将数据重新发送到我的 script.js 文件。 Here is the code这是代码


app.get("/tasks", (req, res) => {
  console.log(req.query.task)
  res.send("hi " + req.query.task)
  MongoClient.connect(url, function(err, db) {
    if (err) throw err
    var dbo = db.db("Cluster0")
    
    var myobj = { task: req.query.task }
    
    dbo.collection("articles").insertOne(myobj, function(err, res) {
     
      if (err) throw err
      console.log("1 document inserted")
      db.close();
      
    })
        var data = JSON.stringify(myobj)

    res.end(data);
    console.log(myobj)
    /*dbo.collection("articles").deleteMany({}, function(err, obj) {
      if (err) throw err;
      console.log(obj.result.n + " document(s) deleted");
      db.close();
    });*/




  })
  
    
})



Here are my errors这是我的错误

ReferenceError: myobj is not defined
    at /home/runner/todolist/index.js:43:29
    at Layer.handle [as handle_request] (/home/runner/todolist/node_modules/express/lib/router/layer.js:95:5)
    at next (/home/runner/todolist/node_modules/express/lib/router/route.js:137:13)
    at Route.dispatch (/home/runner/todolist/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/home/runner/todolist/node_modules/express/lib/router/layer.js:95:5)
    at /home/runner/todolist/node_modules/express/lib/router/index.js:281:22
    at Function.process_params (/home/runner/todolist/node_modules/express/lib/router/index.js:335:12)
    at next (/home/runner/todolist/node_modules/express/lib/router/index.js:275:10)
    at expressInit (/home/runner/todolist/node_modules/express/lib/middleware/init.js:40:5)
    at Layer.handle [as handle_request] (/home/runner/todolist/node_modules/express/lib/router/layer.js:95:5)
(node:7548) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
{ task: 'sadsda', _id: 5efbe175fef3df1d7c5135ce }
1 document inserted
 

As you can see, I can indeed console.log(myobj), so I am not sure why it is not able to be converted with JSON.stringify.如您所见,我确实可以console.log(myobj),所以我不确定为什么它不能用JSON.stringify 转换。 On a side note, if I am able to successfully parse the object into my client side JS file, will the information stay their permanently, or will it be gone if I refresh the webpage?附带说明一下,如果我能够成功地将 object 解析到我的客户端 JS 文件中,这些信息会永久保留,还是刷新网页后会消失? Any ideas on how I can directly take out data from my MongoDB and store the info in my client side JS so that I can display the To-do tasks permanently?关于如何直接从 MongoDB 中取出数据并将信息存储在客户端 JS 中以便我可以永久显示待办事项的任何想法? I hope I am making myself specific.我希望我让自己变得具体。

When you insert myobj , make sure you also then return it, send to client once successfuly saved and then display it however you want:当您插入myobj时,请确保您也将其返回,一旦成功保存就发送给客户端,然后根据需要显示它:

db.collection('articles').insertOne(myobj, function (error, response) {
    if(error) {
        console.log('Error occurred while inserting');
    } else {
       console.log('inserted record', response.ops[0]);
       //send if saved obj is returned
       res.send(response.ops[0])
    }
});

The information will be always refreshed on a client-side (page refresh).信息将始终在客户端刷新(页面刷新)。 You will need to make the call again to grab relevant information from the database.您将需要再次调用以从数据库中获取相关信息。 Of course, you could try to save some information in cookies but that would be an overkill in this case.当然,您可以尝试在cookies中保存一些信息,但在这种情况下,这将是矫枉过正。

In general, it would be ok to do one request to get the list each time client visits the page.一般来说,每次客户访问该页面时,都可以执行一个请求来获取列表。


You only use myobj to save it to your database.您只使用myobj将其保存到您的数据库中。 After that, you should work with the response from the insertOne - newly saved document.之后,您应该使用来自insertOne的响应 - 新保存的文档。

It might be the case that saving the data to the database was not successful - in that case, you do not want to send the object anyway (will be misleading).可能是数据未成功保存到数据库的情况——在这种情况下,您无论如何都不想发送 object(会产生误导)。

For your reference - ops Contains the documents inserted with added _id fields供您参考- ops 包含插入的文档并添加了 _id 字段

response.ops is going to be an array so we need to access the first element of it at an index of 0 - [0] response.ops将是一个数组,因此我们需要在索引 0 - [0]处访问它的第一个元素

I do not think you necessarily need to use JSON.stringify on the backend in this case.在这种情况下,我认为您不一定需要在后端使用JSON.stringify See what works best for you.看看什么最适合你。

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

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