我试图在JSON中添加元素。当我将数据转换为变量并尝试添加时,我能够。但是,当我尝试在MongoDB查找功能中执行相同的操作时,它无法正常工作。这个问题是this
的延续app.get ("/structures", function(req, res){
if(req.query.type=="things"){
mongoOp.thingsSt.find({},'-_id uuid devices', function(err, data) {
var entityID=[];
for (var i =0; i<data.length; i++){
data[i].entityID = "1234";
console.log(data);
}
res.send(data);
});
数据:
[ { devices: { dID: 'TLSM01', deviceList: [Object] },
uuid: 'e863c776-f939-4761-bbce-bf0501b42ef7' },
{ devices: { dID: 'TLSM01', deviceList: [Object] },
uuid: '5a0cd70d-891d-48d8-b205-e92e828ac445' } ]
预期产出:
[ { devices: { dID: 'TLSM01', deviceList: [Object] },
uuid: 'e863c776-f939-4761-bbce-bf0501b42ef7',
entityID: '1234' },
{ devices: { dID: 'TLSM01', deviceList: [Object] },
uuid: '5a0cd70d-891d-48d8-b205-e92e828ac445',
entityID: '1234' } ]
当我尝试使用变量保存我的数据时,我能够实现
var data = [ { devices: { dID: 'TLSM01', deviceList: ["Object"] },
uuid: 'e863c776-f939-4761-bbce-bf0501b42ef7' },
{ devices: { dID: 'TLSM01', deviceList: ["Object"] },
uuid: '5a0cd70d-891d-48d8-b205-e92e828ac445' } ]
for (var i =0;i<data.length;i++){
data[i].entityID = "1234"
}
console.log(data);
答案 0 :(得分:0)
要将新字段添加到mongodb现有集合,您需要更新集合检查此SO Add new field to a collection in MongoDB
> db.foo.find()
> db.foo.insert({"test":"a"})
> db.foo.find()
{ "_id" : ObjectId("4e93037bbf6f1dd3a0a9541a"), "test" : "a" }
> item = db.foo.findOne()
{ "_id" : ObjectId("4e93037bbf6f1dd3a0a9541a"), "test" : "a" }
> db.foo.update({"_id" :ObjectId("4e93037bbf6f1dd3a0a9541a") },{$set : {"new_field":1}})
> db.foo.find()
{ "_id" : ObjectId("4e93037bbf6f1dd3a0a9541a"), "new_field" : 1, "test" : "a" }
答案 1 :(得分:0)
您的数据不是简单的JavaScript对象。它是一个MongoDB文档,因此在查找结果中是只读的。我不确定MongoDB本身是否有.lean
方法,例如MongooseJS提供的方法。无论哪种方式,您都需要首先将MongoDB文档转换为普通的javascript对象。