MongoDB/insertMany

来自康健生活
Kangkk​(留言 | 贡献)2020年6月12日 (五) 09:23的版本 (创建页面,内容为“== 引言 == == 实例 == 某特定场景需要使用 insertMany 生成模拟用户。 {{Hc|models/../user.js|<syntaxhighlight lang="javascript"> var UserSchema = ne…”)
(差异) ←上一版本 | 最后版本 (差异) | 下一版本→ (差异)

引言

实例

某特定场景需要使用 insertMany 生成模拟用户。

models/../user.js
var UserSchema = new Schema({
    loginName: {type: String}, // 登陆账号
    relName: {type: String}, // 真实姓名,MD5加密存储
    secret: {type: String}, // 加密字段
    password: {type: String}, // 加密密码
    email: {type: String}, // 邮箱
    imageUrl: {type: String}, // 头像图片网址
    location: {type: String}, // 居住地
    signature: {type: String}, // 签名
    profile: {type: String}, // 简介
    siteUrl: {type: String}, // 个人网址
    is_lock: {type: Boolean, default: false}, // 是否锁定用户

    article_count: {type: Number, default: 0}, // 文章数量
    meta: {
        create_at: {type: Date, default: Date.now}, // 创建日期
        update_at: {type: Date, default: Date.now}, // 修改日期
    },

    active: {type: Boolean, default: false},
    receive_reply_mail: {type: Boolean, default: false},
    receive_at_mail: {type: Boolean, default: false},

    retrieve_time: {type: Number},
    retrieve_key: {type: String}, // 检索 KEY
    accessToken: {type: String}, //UUID V4
});

UserSchema.plugin(BaseModel);
UserSchema.virtual('avatar_url').get(function () {
    var url = this.avatar || ('https://gravatar.com/avatar/' + utility.md5(this.email.toLowerCase()) + '?size=48');

    // www.gravatar.com 被墙
    url = url.replace('www.gravatar.com', 'gravatar.com');

    // 让协议自适应 protocol,使用 `//` 开头
    if (url.indexOf('http:') === 0) {
        url = url.slice(5);
    }

    // 如果是 github 的头像,则限制大小
    if (url.indexOf('githubusercontent') !== -1) {
        url += '&s=120';
    }

    return url;
});

UserSchema.virtual('isAdvanced').get(function () {
    // 积分高于 700 则认为是高级用户
    return this.score > 700 || this.is_star;
});

UserSchema.index({loginName: 1}, {unique: true});
UserSchema.index({email: 1}, {unique: true});
UserSchema.index({score: -1});
UserSchema.index({githubId: 1});
UserSchema.index({accessToken: 1});

UserSchema.pre('save', function (next) {
    var now = new Date();
    this.update_at = now;
    next();
});

mongoose.model('User', UserSchema);
proxy/../user.js
/**
 * 保存多个 User
 * @function updateOrCreateForMultiuser
 * @param multiuser {array} - 多个用户
 * @param callback
 * @createDate 2020/6/12
 * @update 2020/6/12
 * @author kangjian
 */
exports.updateOrCreateForMultiuser = function (multiuser, callback) {
    User.insertMany(multiuser, callback);
};
analogdata/../user.js
console.time('createRandomConsumer')
    var multiuser = [];
    var iLength = count ? count : 1;
    for (var i = 0; i < iLength; i++) {

        const randomLoginName = stringRandom(16);
        const randomRelName = chineseRandomName.generate();
        const randomSecret = stringRandom();
        const randomPassword = bcrypt.hashSync(stringRandom(10), 10);
        const randomEmail = validator.trim(stringRandom(6, {numbers: false}) + '@' + stringRandom(5, {numbers: false}) + '.' + stringRandom(3, {numbers: false})).toLowerCase();
        const randomImageUrl = 'https://gravatar.com/avatar/test?size=48';
        const randomActive = false;

        multiuser.push({
            loginName: randomLoginName,
            relName: randomRelName,
            secret: randomSecret,
            password: randomPassword,
            email: randomEmail,
            imageUrl: randomImageUrl,
            active: randomActive
        });

        console.log('# Generate new consumer that he name is ' + randomLoginName);
    }
    proxyUser.updateOrCreateForMultiuser(multiuser,
        function (err, obj) {
            if (err) {
                console.log('\033[42;30m # ERR \033[40;32m This is err.\033[0m')
                console.log(err);
                process.exit();
            }
            console.log('# Save user is OK.');
            console.timeEnd('createRandomConsumer')
            var isHasCb = !!cb; // - 用户校验是直接使用 User.js 生成用户,还是其他函数关联 User.js 生成用户
            if (isHasCb) {
                cb(obj._id);
            } else if (pa.length > 2 && pa.slice(2)[0] === 'user') {
                console.log('# End user cli!\n######');
                process.exit();
            }
        });

但是在实际使用过程中,生成速度缓慢并报错。

kangkk@kangkk:~/working/tongdunol$
node ./analogdata/user/user.js user n=200
######
# This in user cli!
# Generate new consumer that he name is EpCdsdVt5pmiAJIc
...
# Generate new consumer that he name is NnXI9tfyIX7a1U30
[2020-06-12 16:17:41.018] [ERROR] cheese - connect to mongodb://127.0.0.1/tongdunol_dev error:  failed to connect to server [127.0.0.1:27017] on first connect [MongoNetworkError: connection 0 to 127.0.0.1:27017 timed out]