Node.Js同步mongdb數據

var objectId = require('mongodb').ObjectId;
const mongoose = require("mongoose");
var SchemaObj = mongoose.Schema;
DB_URL = "mongodb://localhost:27017/admin";

mongoose.connect(DB_URL); //建立連接

/*
 * 鏈接成功
 */
mongoose.connection.on("connected", () => {
    console.log("數據庫鏈接成功!");
});

/**
 * 鏈接異常
 */
mongoose.connection.on("error", err => {
    console.log("數據庫鏈接失敗!" + err);
});

/**
 * 鏈接斷開
 */
mongoose.connection.on("disconnected", () => {
    console.log("數據庫鏈接中斷!");
});

const UserSchema = new SchemaObj({
  name: {
    type: String,
    required: true
  },
  password: {
    type: String,
    required: true
  },
  avatar: {
    type: String
  },
  type:{
    type: String,
    required: true
  },
  date: {
    type: Date,
    default: Date.now
  }
});
const User = mongoose.model("users", UserSchema);

const UserDataSchema = new SchemaObj({
  name: {
    type: String,
    required: true
  },
  password: {
    type: String,
    required: true
  },
  avatar: {
    type: String
  },
  type:{
    type: String,
    required: true
  },
  date: {
    type: Date,
    default: Date.now
  }
});
const UserData = mongoose.model("userData", UserDataSchema);

let query = User.find({});
let pageSize = 2; //查詢數量
let pageCount = 1; //查詢頁碼
let insertFlag = true; //是否添加數據

let setTime = setInterval(() => {
    let startPage = (pageCount - 1) * pageSize; //開始條數
    query.limit(pageSize); //設置查詢條數
    query.skip(startPage); //開始條數
    console.log("pageSize", pageSize, "startPage", startPage, "pageCount", pageCount)
    pageCount += 1;
    query.exec((err, data) => {
        if (err) throw err;
        if (data.length < pageSize) {
            console.log('close');
            clearInterval(setTime);
        }
        for (var i = 0; i < data.length; i++) {
            const userData = new UserData({
                _id: data[i]._id,
                name: data[i].name,
                password: data[i].password,
                type: data[i].type,
                avatar: data[i].avatar,
                date: data[i].date
            });
            //去除重複數據
            UserData.findOne({
                    _id: objectId(data[i]._id)
                },
                function (err, doc) {
                    if (err) throw err;
                    if (doc != null) {
                        insertFlag = false;
                    }
                }
            );
            if (insertFlag) {
                userData
                    .save()
					.then('同步數據: ' + JSON.stringify(userData))
                    .catch(err => console.log(err));
            }
        }
    });
}, 1000);
相關文章
相關標籤/搜索