[英]Cannot assign to read only property '_id' of
I have a Node.js app. 我有一个Node.js应用程序。 This is the first time that I'm tring to use MongoDB.
这是我第一次使用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"} 无法分配给{“title”的只读属性'_id':“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. 我听说_id是Mongo应该自己创造的价值。 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.
我发现很多问题都有相同的例外,但要么不是_id字段,要么是_id字段,但在客户端,他们根本没有帮助我。
Any help will be profoundly appreciated! 任何帮助将深表感谢!
The whole code: 整个代码:
mongo-manager.js: 蒙戈 - 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: 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;
Omit the JSON.stringify
call and just pass req.body
to addPost
. 省略
JSON.stringify
调用,只需将req.body
传递给addPost
。 insertOne
needs an object, not a string. insertOne
需要一个对象,而不是一个字符串。
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. 至于为什么会导致该特定错误消息:
insertOne
将向作为doc
参数传递的值添加唯一的_id
属性(如果它尚不存在),但字符串是只读(不可变)对象,因此它可以不要添加_id
。
I had a similar problem and it was because of the obj
given was a string
我有一个类似的问题,因为给出的
obj
是一个string
and you can't set properties of strings
而且你不能设置
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. 这个JS代码是在浏览器上运行的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.