Mongoose v3.6+는 이제 배치 삽입을 지원합니까? I'는 몇 분 동안 검색했지만 이 질문에 일치하는 것은 몇 년 전이며 대답은 분명 아니오였습니다.
편집:
나중에 참조하기 위해, 답은 "Model.create()"를 사용하는 것이다. 'createfilename'은 배열을 첫 번째 인수로 받아들이므로 문서를 전달하여 배열로 삽입할 수 있습니다.
"모델스크레이트 ()" 은 잘못된 방법으로 삽입물의 다룰 경우 매우 큰 불크. 매우 느린 것. 이 경우 콩지름에 "모델스콜레스티온.린스트" 내가 긁어줄게 수행하는 , . "모델스크레이트 () '의 크기에 따라 불크 이시목이를 철썩! 함께 했던 만 문서, 아니 운빨이야. "모델스콜레스티온.린스트" 的概念 사용하여 불과 몇 초.
Model.collection.insert(docs, options, callback)
var Potato = mongoose.model('Potato', PotatoSchema);
var potatoBag = [/* a humongous amount of potato objects */];
Potato.collection.insert(potatoBag, onInsert);
function onInsert(err, docs) {
if (err) {
// TODO: handle error
} else {
console.info('%d potatoes were successfully stored.', docs.length);
}
}
이제, 몽구스, h1> < 4.4.0 汲摹窍妨绰 불크 insert< /h1>; 몽구스 (참 - 불크 삽입하십시오 4.4.0 cxp 모델과 함께 콜린스트마니 메서드로부터 ' ()'. 이는 보다 자크레이트 () '또는' 에 '루프을 운행에서어떠한 도움을 제공하고 있는 어레이입니다.
사용법:
var rawDocuments = [/* ... */];
Book.insertMany(rawDocuments)
.then(function(mongooseDocuments) {
/* ... */
})
.catch(function(err) {
/* Error handling */
});
또는
Book.insertMany(rawDocuments, function (err, mongooseDocuments) { /* Your callback function... */ });
대한 쉽게 추적할 수 있습니다.
그러나, create" " 사용할 수 있습니다. 몽구스, 문서, 이 슬라이드에서는 배열입니다 방법을 포함될 수 있습니다. (예:
Candy.create({ candy: 'jelly bean' }, { candy: 'snickers' }, function (err, jellybean, snickers) {
});
콜백 함수를 삽입됨 문서에 포함되어 있습니다. 항상 알 수 없습니다 (고정 길이 인수 등 위) 가 얼마나 많은 항목에서와 삽입됨 루프 수 있도록 그들을 통해:
var insertedDocs = [];
for (var i=1; i<arguments.length; ++i) {
insertedDocs.push(arguments[i]);
}
더 좋은 솔루션이 될 것 "이라며" "사용할 캔디스콜레스티온.린스트 ()" 대신 "캔디스크레이트 ()" - 위의 예에서 사용된 - 같도다라고 it& # 39 의 빠른 (만들기 " () '를 주장하고 있다" 모델리자베 () "의 각 항목을 그러하매 it& # 39 의 느린).
자세한 내용은 몽고 문서 참조. http://docs.mongodb.org/manual/reference/method/db.collection.insert/
( 더 포인팅 아르셀던 덕분에 이 아웃하려면)
몽구스 등을 사용하여 삽입하십시오 최고 점수를 오토메이티드 불크 수행할 수 있습니다. 그러나 이 파일은 uxfs 사용할 수 없습니다.
/* a humongous amount of potatos */
var potatoBag = [{name:'potato1'}, {name:'potato2'}];
var Potato = mongoose.model('Potato', PotatoSchema);
Potato.collection.insert(potatoBag, onInsert);
function onInsert(err, docs) {
if (err) {
// TODO: handle error
} else {
console.info('%d potatoes were successfully stored.', docs.length);
}
}
다음은 제이르마니 및 저장 데이터를 저장하는 방법을 모두 사용하여
/* write mongoose schema model and export this */
var Potato = mongoose.model('Potato', PotatoSchema);
/* write this api in routes directory */
router.post('/addDocuments', function (req, res) {
const data = [/* array of object which data need to save in db */];
Potato.insertMany(data)
.then((result) => {
console.log("result ", result);
res.status(200).json({'success': 'new documents added!', 'data': result});
})
.catch(err => {
console.error("error ", err);
res.status(400).json({err});
});
})
이러한 문서는 저장으로의 평행광.
/* write mongoose schema model and export this */
var Potato = mongoose.model('Potato', PotatoSchema);
/* write this api in routes directory */
router.post('/addDocuments', function (req, res) {
const saveData = []
const data = [/* array of object which data need to save in db */];
data.map((i) => {
console.log(i)
var potato = new Potato(data[i])
potato.save()
.then((result) => {
console.log(result)
saveData.push(result)
if (saveData.length === data.length) {
res.status(200).json({'success': 'new documents added!', 'data': saveData});
}
})
.catch((err) => {
console.error(err)
res.status(500).json({err});
})
})
})
몽구스 한계가 있을 것 같다, 1000년 이상의 문서를 사용할 때 사용하는 것이
Potato.collection.insert(potatoBag, onInsert);
사용할 수 있습니다.
var bulk = Model.collection.initializeOrderedBulkOp();
async.each(users, function (user, callback) {
bulk.insert(hash);
}, function (err) {
var bulkStart = Date.now();
bulk.execute(function(err, res){
if (err) console.log (" gameResult.js > err " , err);
console.log (" gameResult.js > BULK TIME " , Date.now() - bulkStart );
console.log (" gameResult.js > BULK INSERT " , res.nInserted)
});
});
하지만 이는 거의 두 배 빠른 테스트 때 함께 10000mb 문서:
function fastInsert(arrOfResults) {
var startTime = Date.now();
var count = 0;
var c = Math.round( arrOfResults.length / 990);
var fakeArr = [];
fakeArr.length = c;
var docsSaved = 0
async.each(fakeArr, function (item, callback) {
var sliced = arrOfResults.slice(count, count+999);
sliced.length)
count = count +999;
if(sliced.length != 0 ){
GameResultModel.collection.insert(sliced, function (err, docs) {
docsSaved += docs.ops.length
callback();
});
}else {
callback()
}
}, function (err) {
console.log (" gameResult.js > BULK INSERT AMOUNT: ", arrOfResults.length, "docsSaved " , docsSaved, " DIFF TIME:",Date.now() - startTime);
});
}
내가 예전에는 비동기 포리치 (https://partner. 비동기 포리치 대해 고궁박물원 패키지로의 문서용으로) 를 developer. 마찬가지다.
내 코드를 스니핏 다음과 같이 있다. I am getting 문서에서 레크롬보디스
var forEach = require('async-foreach').forEach;
exports.save_Ctrl = function (req, res) {
// var l=req.body;
// console.log("length:",l.length);
forEach(req.body, function(item, index, object,err) {
console.log(req.body[index]);
var post = new saveObj(req.body[index]);
//save model to MongoDB
post.save(function (err) {
if (err) {
console.log('error saving :' + err.message);
return err;
}
else {
console.log("Post saved");
}
});
});
}
작업 및 관련 코드를 공유) 의 프로젝트:
//documentsArray is the list of sampleCollection objects
sampleCollection.insertMany(documentsArray)
.then((res) => {
console.log("insert sampleCollection result ", res);
})
.catch(err => {
console.log("bulk insert sampleCollection error ", err);
});