Using Mongoose 4.2.9 with MongoDB 3 and the following data set:
- Database:
test
- Collections:
images
,albums
I am trying to remove the images that belongs to no albums
.
Sample document for albums
collections:
> db.albums.findOne()
{
"_id" : 0,
"images" : [
2433,
2753,
2983,
6510,
99334
]
}
Here images
is an array of _id
's from images
collection.
Sample data for images
collection:
> db.images.findOne()
{
"_id" : 243,
"height" : 480,
"width" : 640
}
I have written the following code using node to achieve the mentioned goal:
var mongoose = require('mongoose');
/* Construct Album model */
var albumSchema = mongoose.Schema({
_id: Number,
images: [Number]
});
var Album = mongoose.model('Album', albumSchema);
/* Construct Image model */
var imageSchema = mongoose.Schema({
_id: Number
});
var Image = mongoose.model('Image', imageSchema);
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error'));
db.once('open', doTheJob);
/* Do the job */
function doTheJob () {
Image.find({}, function (err, images) {
if (err) {
throw err;
}
for(var i in images){
(function (image) {
Album.aggregate([
{
$unwind: "$images"
}, {
$group: {
_id: "$images"
}
}, {
$match: {
_id: image._id
}
}
])
.exec(function (err, albums) {
if (err) {
throw err;
}
if (albums.length === 0) {
console.log(image._id);
Image.remove({_id: image._id}, function(err){
if (err) {
console.log(err);
throw err;
}
console.log("Removed " + image._id);
});
/* Also the following code does not work, image (with
* lowercase 'i' is a doc that is returned by Image.find({}))
image.remove( function(err){
if (err) {
console.log(err);
throw err;
}
console.log("Removed " + image._id);
});
*/
}
});
})(images[i]);
}
});
}
Now my problem is Image.remove()
is not called, since in console, I cannot see the error nor Removed XXX
, also I tested the docs in console too.
I need to mention, if in the same program, instead of doTheJob()
, I pass a callback with only a Image.remove({_id: XXX}, function () {})
, then it works.