【问题标题】:TypeError : Cannot assign to read only property '_id' of { ... }TypeError:无法分配给 { ... } 的只读属性“_id”
【发布时间】:2017-03-08 23:51:51
【问题描述】:

我正在尝试使用POST 方法获取键盘字符串并将其保存在mongoDB 中。服务器启动了,但是我无法将输入写入数据库,因为控制台返回如下错误:

TypeError : Cannot assign to read-only property '_id' of {the text that I entered through html page}.

我从很小的时候就开始使用nodejs和mongodb,我需要帮助...感谢您的关注:)

server.js:

const express = require('express');
const bodyParser= require('body-parser');
const app = express();

app.use(bodyParser.urlencoded({ extended: true }));

var MongoClient = require('mongodb').MongoClient
var assert = require('assert');

var url = 'mongodb://localhost:27017/data'; 

// Use connect method to connect to the Server

MongoClient.connect(url, function(err, db) {

 assert.equal(null, err);
 console.log("Connected correctly to server");

 app.listen(3000, function() {

  console.log('listening on 3000');

  app.get('/index.html', function (req, res) {
  res.sendFile( __dirname + "/" + "index.html" );
  });

  app.post('/process_post', function(req, res){

  response={r:req.body.s};  

  var risp=JSON.stringify(response);  

  res.end(risp);

  console.log("Insert : "+risp); 

    //"text" is an existing collection of mongodb "data" locally

  var collection = db.collection('text'); 

    collection.insert(risp); 

  }); 

 }); 

db.close();

});

index.html:

<!DOCTYPE html>
<html>
   <body>

      <form action = "http://127.0.0.1:3000/process_post" method = "POST">
         Input: <input "text" name=s >  <br>

         <button type = "submit">Submit</button>
      </form>

   </body>
</html>

【问题讨论】:

    标签: node.js mongodb post mongodb-query node-webkit


    【解决方案1】:

    发生错误是因为您试图将字符串添加到数据库。您应该插入对象。不要插入risp,而是尝试插入response var 看看它是否有效。还要注意插入是异步的,所以考虑添加一个回调函数。见this example,方法不同但逻辑应该是一样的。

    【讨论】:

    • 这样做不会得到更多先前的错误但插入过程没有完成......也就是说,服务器运行但从未完成POST。不要在数据库中插入任何内容,“每次”使用屏幕上的提交打印,console.log ( "Insert:" + resp); 以下行:“插入:[object Obeject]。如果我考虑代码行:res.end (resp); 我得到了以下错误:TypeError: first argument must be a string or Buffer. 感觉有点绝望..
    • 响应**不响应
    猜你喜欢
    • 2019-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 2015-08-05
    相关资源
    最近更新 更多