向 node.js 中现有的 json 对象添加一个新属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14768132/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add a new attribute to existing json object in node.js
提问by Prats
I have an object like this
我有一个这样的对象
==================records=========={ Id: 5114a3c21203e0d811000088,
userId: 'test',
sUserId: test,
userName: 'test',
url: 'test',
Title: 'test'
}
I need to add a new field Name : 'test'to the above record, I tried giving records.Name = name, it didn't work.
我需要在上面的记录中添加一个新字段Name : 'test',我尝试给 record.Name = name,它没有用。
Helps please
请帮助
Thanks, Prats
谢谢,普拉茨
采纳答案by Haywire
Those finding this problem, OP mentioned in a comment below the original question that the solution for this problem is:
发现此问题的人,OP 在原始问题下方的评论中提到此问题的解决方案是:
records.set('Name', 'test')
This adds a new attribute called Namehaving value test.
这将添加一个名为Namehas value的新属性test。
回答by droider
I am assuming you are trying to add a property to a returned Mongoose Document to reuse it somewhere else. Documents returned by Mongoose are not JSON objects directly, you'll need to convert them to an object to add properties to them. The following should work:
我假设您正在尝试将属性添加到返回的 Mongoose 文档以在其他地方重用它。Mongoose 返回的文档不是直接的 JSON 对象,您需要将它们转换为对象以向它们添加属性。以下应该工作:
//... record is a mongoose Document
var r = record.toObject();
r.Name = 'test';
console.log("Record ",r);
回答by bombayquant
Just use,
就用,
var convertedJSON = JSON.parse(JSON.stringify(mongooseReturnedDocument);
and Then,
进而,
convertedJSON.newProperty = 'Hello!'
'Hello!' can be anything, a number, a object or JSON Object Literal.
'你好!' 可以是任何东西、数字、对象或 JSON 对象文字。
Cheers! :)
干杯! :)
回答by majorobot
I experienced a similar problem, and hope that my hours of existential frustration help others in the same situation. My inclination was to believe that documents returned via Mongoose are read-only. This is actually not true.
我遇到了类似的问题,希望我数小时的生存挫折能帮助处于同样情况的其他人。我倾向于相信通过 Mongoose 返回的文档是只读的。这实际上不是真的。
However, you cannot assign a property to your document that is not also in your Schema.
但是,您不能将不在您的架构中的属性分配给您的文档。
So, unless your schema has the following:
因此,除非您的架构具有以下内容:
{
Name: {String}
}
you will be constantly frustrated by trying to assign Name to your document.
尝试为您的文档指定 Name 时,您会经常感到沮丧。
Now, there are workarounds in the answers above that also worked for me, but they do not get to the root of the problem:
现在,上面的答案中有一些解决方法也对我有用,但它们没有找到问题的根源:
myDocument.toObject();
JSON.parse(JSON.stringify(myDocument);
These will work, but in my opinion they just hide the problem. The real issue is that Mongoose is smarter than we realized and is enforcing your schema, as it should.
这些会起作用,但在我看来,它们只是隐藏了问题。真正的问题是 Mongoose 比我们意识到的更聪明,并且正在执行您的架构,因为它应该。
回答by Leonardo Dalcin
You could also use the lean()method, e.g. const users = await Users.find().lean().exec()
您也可以使用Lean()方法,例如const users = await Users.find().lean().exec()
From the mongoose documentation:
从猫鼬文档:
Documents returned from queries with the lean option enabled are plain javascript objects, not MongooseDocuments. They have no save method, getters/setters or other Mongoose magic applied
从启用了精简选项的查询返回的文档是普通的 javascript 对象,而不是 MongooseDocuments。他们没有应用保存方法、getter/setter 或其他猫鼬魔法
回答by venoel
My variant.
我的变种。
If schema defined with {strict:false}you can simply add new property by
如果模式定义为{strict:false}您可以简单地添加新属性
recorcd.newProp = 'newvalue';
recorcd.newProp = 'newvalue';
If schema defined with {strict:true}you can either convert Mongoose object to object as mentioned earlier or use command
如果使用{strict:true}您定义的模式可以将 Mongoose 对象转换为前面提到的对象或使用命令
record.set('newProp','newValue',{strict:false})
record.set('newProp','newValue',{strict:false})
See http://mongoosejs.com/docs/api.html#document_Document-schema
请参阅http://mongoosejs.com/docs/api.html#document_Document-schema
回答by neelsg
If you have loaded this object into records, both records.Name = "test"or records['Name'] = "test"will work. You have either not loaded the object correctly, or are inserting an undefined value into it.
如果您已将此对象加载到 中records,则两者records.Name = "test"或records['Name'] = "test"都将起作用。您没有正确加载对象,或者正在向其中插入未定义的值。
To test: add console.log(records.userId), this should print 'test' to the terminal.
要测试: add console.log(records.userId),这应该在终端上打印“test”。
Also add console.log(name). If you get ReferenceError: name is not defined, you obviously cannot do: records.Name = name
还添加console.log(name). 如果你得到ReferenceError: name is not defined,你显然不能这样做:records.Name = name

