Alon Alon - 5 months ago 76
Node.js Question

Cannot assign to read only property '_id' of

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;

Answer

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.