我在 MongoDB 数据库中有两个集合:“照片”和“相册”。
相册集合中的每个文档都包含一个“图像”属性,该属性包含一个 ID 数组,这些 ID 是返回照片集合的键。
我需要使用 Node.js 驱动程序遍历相册集合并删除孤立图像,即不在任何相册中的图像。
我好像想不通...这是我写的代码
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/photosharing', function(err, db) {
if(err) throw err;
var images = db.collection('images');
var albums = db.collection('albums');
var myArray = [];
db.albums.count({}, function(err, count) {
if(err) throw err;
console.dir("start length of albums is " + count);
});
images.find({}).toArray(function(err, docs) {
if(err) throw err;
for (var i=1; i<=docs.length; i++) {
albums.count({"images": i}, function(err, count) {
if(err) throw err;
if ( count == 0 ) {
images.remove({images.find({ "_id": i })})
}
});
};
});
db.albums.count({}, function(err, count) {
if(err) throw err;
console.dir("end length of albums is " + count);
});
db.close();
});
最佳答案
这是满足您需要的代码。
但是,我会建议你之前尝试几次,然后再尝试几次,然后再寻求其他人的帮助,因为看起来你已经尝试了一种方法 - 没有奏效并且没有尝试其他选项,而在开发总是有很多方法来实现“相同”的东西。
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/photosharing', function(err, db) {
if(err) throw err;
var images = db.collection('images');
var albums = db.collection('albums');
var imageIds = [ ];
var imageIdKeys = { };
albums.find({ }).toArray(function(err, data) {
if (!err) throw err;
for(var i = 0; i < data.length; i++) {
for(var n = 0; n < data[i].images.length; n++) {
if (!imageIdKeys[data[i].images[n]]) {
imageIdKeys[data[i].images[n]] = true;
imageIds.push(data[i].images[n]);
}
}
}
images.remove({ _id: { $nin: imageIds } }, function(err) {
if (!err) throw err;
db.close();
});
});
});
它将收集图像的所有 ID,防止 ID 重复。这也可以以更好的方式使用聚合来完成,但我决定使用 node.js 逻辑来收集 ID。然后它将从 images
集合中删除所有 ID 未在 imageIds
数组中提及的文档。
只有在所有操作完成后 - 关闭数据库连接。
关于javascript - 使用 Node.jS 驱动程序在 MongoDB 中迭代多个集合并比较结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19084821/