[社区环境搭建] 替换七牛图片前缀
发布于 5 年前 作者 qjzd 1744 次浏览 最后一次编辑是 2 年前 来自 码农

替换user头像前缀

var cursor=db.getCollection('users').find({});
while(cursor.hasNext()) {
    var user = cursor.next();
    var avatar = user.avatar;
    avatar = avatar.replace("https://nzijkk7pu.qnssl.com", "https://qiniu.qjzd.net");
    db.getCollection('users').update({"_id": user._id}, {$set: {"avatar": avatar}});
	print(user.email);
}

替换topic的内容图片前缀

var cursor = db.getCollection('topics').find({});
while(cursor.hasNext()) {
    var topic = cursor.next();
    var content = topic.content;
    var index = content.indexOf("https://nzijkk7pu.qnssl.com");
    if (index != -1) {
        content = content.replace(new RegExp("https://qiniu.qjzd.net","gm"), "https://qiniu.qjzd.net");
        db.getCollection('topics').update({"_id": topic._id}, {$set: {"content": content}});
		print(topic.title);
    }
}

替换replies内容中的图片前缀

var cursor = db.getCollection('replies').find({});
while(cursor.hasNext()) {
    var replies = cursor.next();
    var content = replies.content;
    var index = content.indexOf("https://nzijkk7pu.qnssl.com");
    if (index != -1) {
        content = content.replace(new RegExp("https://qiniu.qjzd.net","gm"), "https://qiniu.qjzd.net");
        db.getCollection('replies').update({"_id": replies._id}, {$set: {"content": content}});
        print(content);
    }
}

使用mongo执行js脚本

mongo 127.0.0.1:27017/qjzd_club_dev replaceQiniuImage.js

1 回复
//var oldQiniuUrl = "https://nzijkk7pu.qnssl.com";
//var newQiniuUrl = "https://qiniu.qjzd.net";
var oldQiniuUrl = "https://nzijkk7pu.qnssl.com";
var newQiniuUrl = "https://qiniu.qjzd.net";
var cursor=db.getCollection('users').find({});
while(cursor.hasNext()) {
    var user = cursor.next();
    var avatar = user.avatar;
    if (avatar.indexOf(oldQiniuUrl)  !=  -1) {
        avatar = avatar.replace(oldQiniuUrl, newQiniuUrl);
        db.getCollection('users').update({"_id": user._id}, {$set: {"avatar": avatar}});
        print(user.email);
    }
}

var cursor = db.getCollection('topics').find({});
while(cursor.hasNext()) {
    var topic = cursor.next();
    var content = topic.content;
    if (content.indexOf(oldQiniuUrl) != -1) {
        content = content.replace(new RegExp(oldQiniuUrl, "gm"), newQiniuUrl);
        db.getCollection('topics').update({"_id": topic._id}, {$set: {"content": content}});
        print(topic.title);
    }
}

var cursor = db.getCollection('replies').find({});
while(cursor.hasNext()) {
    var replies = cursor.next();
    var content = replies.content;
    if (content.indexOf(oldQiniuUrl) != -1) {
        content = content.replace(new RegExp(oldQiniuUrl,"gm"), newQiniuUrl);
        db.getCollection('replies').update({"_id": replies._id}, {$set: {"content": content}});
        print(content);
    }
}
回到顶部