admin管理员组

文章数量:1344336

I have a Node.js app. This is the first time that I'm tring to use MongoDB.

I get this exception when I try to insert a document:

Cannot assign to read only property '_id' of {"title":"some title","content":"some content","tags":"#some #tags"}

This is the line of code where it occurs:

db.collection(collectionName).insertOne(json, callback);

I've heard that _id is a value that Mongo's supposed to create by itself. I've found many questions with the same exception but either not with the _id field or with the _id field but in client side and they didn't help me at all.

Any help will be profoundly appreciated!

The whole code:

mongo-manager.js:

var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/blog';

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

        func(db, function(err, result) {
            db.close();
        });
    });
}

function insertOne(db, collectionName, json, callback){
    db.collection(collectionName).insertOne(json, callback);
}

exports.addPost = function(json) {
    performOperation(func);

    function func (db, callback) {
        insertOne(db, "posts", json, callback)
    }
};

index.js:

var express = require('express');
var router = express.Router();

router.post('/posts', function(req, res, next){
  var mongoManager = require('../dal/mongo-manager.js');
  mongoManager.addPost(JSON.stringify(req.body));
});

module.exports = router;

I have a Node.js app. This is the first time that I'm tring to use MongoDB.

I get this exception when I try to insert a document:

Cannot assign to read only property '_id' of {"title":"some title","content":"some content","tags":"#some #tags"}

This is the line of code where it occurs:

db.collection(collectionName).insertOne(json, callback);

I've heard that _id is a value that Mongo's supposed to create by itself. I've found many questions with the same exception but either not with the _id field or with the _id field but in client side and they didn't help me at all.

Any help will be profoundly appreciated!

The whole code:

mongo-manager.js:

var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/blog';

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

        func(db, function(err, result) {
            db.close();
        });
    });
}

function insertOne(db, collectionName, json, callback){
    db.collection(collectionName).insertOne(json, callback);
}

exports.addPost = function(json) {
    performOperation(func);

    function func (db, callback) {
        insertOne(db, "posts", json, callback)
    }
};

index.js:

var express = require('express');
var router = express.Router();

router.post('/posts', function(req, res, next){
  var mongoManager = require('../dal/mongo-manager.js');
  mongoManager.addPost(JSON.stringify(req.body));
});

module.exports = router;
Share Improve this question edited Feb 7, 2016 at 15:27 Alon asked Feb 7, 2016 at 14:45 AlonAlon 12k28 gold badges103 silver badges172 bronze badges 4
  • Can you show how you are creating json? insertOne will add a unique _id property to it if it doesn't already exist, but your json object appears to be a read-only object. – JohnnyHK Commented Feb 7, 2016 at 15:05
  • @JohnnyHK I appended the required code to my question. – Alon Commented Feb 7, 2016 at 15:14
  • Omit the JSON.stringify call and just pass req.body to addPost. insertOne needs an object, not a string. – JohnnyHK Commented Feb 7, 2016 at 15:17
  • Oh I'm stupid! I wanted to convert it from JavaScript object to JSON for omitting the prototype but instead I converted it to string. @JohnnyHK well done. Please write it as an answer. – Alon Commented Feb 7, 2016 at 15:26
Add a ment  | 

2 Answers 2

Reset to default 8

Omit the JSON.stringify call and just pass req.body to addPost. insertOne needs an object, not a string.

As to why this is causing that specific error message: insertOne will add a unique _id property to the value passed as the doc parameter it if it doesn't already exist, but a string is a read-only (immutable) object so it can't add _id to it.

I had a similar problem and it was because of the obj given was a string

and you can't set properties of strings

this solved my problem:

if(window.Prototype) {
       delete Object.prototype.toJSON;
       delete Array.prototype.toJSON;
       delete Hash.prototype.toJSON;
       delete String.prototype.toJSON;
}

The JS code were this occurs was running on the browser.

本文标签: javascriptCannot assign to read only property 39id39 ofStack Overflow