2016-10-26 7 views
0

POSTメソッドを使用して、キーボードストリングを取得してmongoDBに保存しようとしています。サーバーが開始されたが、コンソールには、次のエラーを返しますので、私は、データベースへの入力を書き込むことはできません。TypeError:{...}の読み取り専用プロパティ '_id'に割り当てることができません

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> 

答えて

1

エラーは、文字列をデータベースに追加しようとしているために発生します。オブジェクトを挿入する必要があります。 rispを挿入する代わりに、responseのvarを挿入して、動作するかどうか確認してください。また、挿入が非同期であることに注意してください。したがって、コールバック関数を追加することを検討してください。 this exampleを参照してください。方法は異なりますが、ロジックは同じにする必要があります。

+0

これを行うと以前のエラーは発生しませんが、挿入プロセスが完了していません。つまり、サーバーは実行されますがPOSTは完了しません。 'console.log(" Insert: "+ resp);で画面上の印刷を使用する"毎回 "何もデータベースに挿入しないでください。次の行:" Insert:[オブジェクトオブジェクト] If私はコード行を考えます: 'res.end(resp);'次のエラーが出ます:TypeError:最初の引数は文字列またはバッファでなければなりません。 私は少し欲求不満です。 –

+0

レスポンス** not resp –

関連する問題