不能分配给只读属性“_id”

Cannot assign to read only property '_id' of

本文关键字:id 只读属性 不能分 分配 不能      更新时间:2023-09-26

我有一个Node.js应用程序。这是我第一次尝试使用MongoDB。

当我尝试插入文档时,我收到此异常:

无法将 {"title":"某些标题"、"内容":"某些内容"、"标记":"#some #tags"} 分配给只读属性"_id

"

这是它发生的代码行:

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

我听说_id是Mongo应该自己创造的价值。我发现了很多问题,但要么不是_id字段,要么是_id字段,而是在客户端,它们根本没有帮助我。

任何帮助将不胜感激!

整个代码:

蒙戈经理.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)
    }
};

索引.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;

JSON.stringify调用,只需将req.body传递给addPostinsertOne需要一个对象,而不是一个字符串。

至于为什么这会导致该特定错误消息:如果它不存在,insertOne会将唯一的_id属性添加到作为doc参数传递的值中,但字符串是只读(不可变)对象,因此它无法向其添加_id

我遇到了类似的问题,这是因为给出的obj是一个string

并且无法设置strings的属性

这解决了我的问题:

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

发生这种情况的JS代码在浏览器上运行。