如何使用Monk在Javascript中更新forEach循环中的文档?
首先是我的文件结构:如何使用Monk在Javascript中更新forEach循环中的文档?,javascript,mongodb,monk,Javascript,Mongodb,Monk,首先是我的文件结构: { "_id": "541a8bea74123744b371d38e", "geometry": { "type": "Point", "coordinates": [ 5.3435, 51.69554 ] }, "type": "Feature", "properties": { } } 问题是我想在forEach循环中使用update函数添加一个字段。循环可以工作,我可以迭代集合中的每个文档,但u
{
"_id": "541a8bea74123744b371d38e",
"geometry": {
"type": "Point",
"coordinates": [
5.3435,
51.69554
]
},
"type": "Feature",
"properties": {
}
}
问题是我想在forEach循环中使用update函数添加一个字段。循环可以工作,我可以迭代集合中的每个文档,但update函数什么也不做。这就是我所拥有的:
var counter = 0;
collection.find({}, {
stream: true
})
.each(function(doc) {
counter++;
var hash = geohash.encode(doc.geometry.coordinates[1], doc.geometry.coordinates[0], precision = 9);
console.log("id: " + doc._id + " hash: " + hash + " counter= " + counter);
collection.update({
_id: doc._id
}, {
$set: {
"properties.geohash.precision9": hash
}
},
function(err) {
if (err) console.log(err);
}
);
})
.error(function(err) {
// handle error
console.log(err);
})
.success(function(doc) {
// final callback
console.log("added geohash");
res.send({
objects: doc
});
});
我错在哪里?MongoDb shell中的工作代码
db.collection.find().forEach(function(item)
{
var hash = ....;
item.properties.geohash.precision9 = hash;
db.collection.save(item);
})
我相信只要稍作改动,你就可以将它用于monk我相信你的问题在于你选择的模式。属性是一个子文档,其中存储的项可以通过“.”访问,但您正在尝试设置另一个子文档的属性。Monk是一个非常轻量级的MongoDB驱动程序,不支持这么多级别的子文档。我建议将您的模式更改为以下内容:
{
"_id": "541a8bea74123744b371d38e",
"geometry": {
"type": "Point",
"coordinates": [
5.3435,
51.69554
]
},
"type": "Feature",
"properties": {
},
"geohash": {
"precision9": "somevalue"
}
}
我会尝试通过删除子文档来平展文档结构。在我看来,拥有名为properties的子文档是多余的,因为有关当前文档的信息直接与父级相关。除非我不理解你的数据。如果是这种情况,请提供更多存储在数据库中的文档,尤其是那些具有percision9或其他3个深度属性值的文档
您可以做的一件事,尽管有点难看,就是使用一个额外的变量来构建子文档,并分配值“hash”,然后将属性设置为与该新变量相等。这将覆盖以前存储在属性中的任何内容,除非您正确处理它:
var newProperties = {
geohash: {
presision9: hash
}
}
collection.update({
_id:doc.\u id
}, {
$set:{
“属性”:新属性
}
},
功能(err){
if(err)console.log(err);
}
);
})
问题是如果有或没有id,save方法会在MongoDB中更新或插入文档。因此,在Monk中,您可以使用update或insert命令。您可以使用db.collection.update(item.\u id,item);