我只是習慣於承諾,我想添加一個額外的ObjectId引用到表。我使用此代碼:如何立即執行貓鼬查詢並用Promise.all等待它們?
'use strict';
const mongoose = require('mongoose');
const config = require('config');
mongoose.connect(config.get("DBUrl"), {useMongoClient: true});
mongoose.set('debug', true);
require('../model/AnnotationRequest');
require('../model/Website');
const AnnotationRequest = mongoose.model('AnnotationRequest');
const Website = mongoose.model('Website');
foo(function() {
console.log('done');
});
function foo(done) {
Website.find()
.then(function (websites) {
if (!websites) console.error('could not find any websites');
AnnotationRequest.find({website: {$exists: false}})
.then(function (annotationRequests) {
let jobs = [];
for (let k = 0; k < annotationRequests.length; k++) {
let found = false;
for (let i = 0; i < websites.length; i++) {
let websiteAnnotations = websites[i].annotations;
for (let o = 0; o < websiteAnnotations.length; o++) {
if (websiteAnnotations[o].equals(annotationRequests[k].annotation)) {
found = true;
annotationRequests[k].website = websites[i];
jobs.push(
annotationRequests[k].save()
.then(function (res) {
console.log("success saving", res._id);
}).catch(function (err) {
console.error(err);
done(err);
})
);
break;
}
}
if (found) {
break;
}
}
}
Promise.all(jobs).then(
function() {
done();
}
).catch(function (err) {
console.error(err);
});
});
});
}
第一個保存查詢被報告在Promise.all語句中啓動。是否在第一個.save()
聲明後不立即執行查詢?我怎樣才能立即啓動它們?
另一個問題是,對於200k條目,此代碼需要2個小時。在服務器上,我們有> 2M條目。不知道它是否會起作用。有什麼建議麼?
感謝
要執行大量插入我可以強烈建議你看看批量操作(https://docs.mongodb.com/manual/reference/method/Bulk/)。 –