使用mongoose从数据库中一次性find出数据,提示:
但是我查了default the memory limit of Node.js is 512 mb,我的数据集合大小只有127MB,并没有超过这个大小,也不需要设置--max_old_space_size吧,求解
代码如下:
//model.js
var LagouInfo = require('./schema.js')
var DesData = require('./des.js');
var async = require('async');
LagouInfo.find({}, function(res){
res.forEach(function(item){
if(item.content.trim()){
var sumSalary = 0;
item.salary.forEach(function(sitem){
var num;
if(sitem.indexOf('-') == -1){
num = sitem.replace(/\D+/, '');
}else{
num = parseInt(sitem.trim().split('-')[1]);
}
// console.log(sitem, num);
sumSalary += num;
})
var tags = item.tag.trim().split(',');
tags.forEach(function(tag){
DesData.update({'tag': tag}, {$push: {'content': item.content}});
DesData.update({'tag': tag}, {$inc: {'total': item.total}});
DesData.update({'tag': tag}, {$inc:{'salary': sumSalary}});
})
}
})
})
//des.js
var mongoose = require('./db.js'),
Schema = mongoose.Schema;
var InfoSchema = new Schema({
tag: {type: String},
content: {type: Array},
total: {type: Number},
salary: {type: Number},
});
var Data = mongoose.model('desdata', InfoSchema, 'desdata');
function insert(obj, callback){
var data = new Data(obj);
data.save(function(err, res){
if(err) console.log('Error:' + err);
else callback(null, res);
})
}
function update(conditions, updateStr){
Data.update(conditions, updateStr, function(err, res){
if(err) console.log('Error:' + err);
else console.log('Update Success');
// else callback(null, res);
})
}
function find(conditions, callback){
Data.find(conditions, function(err, res){
if(err) console.log('Error:' + err);
else callback(res);
})
// return Data.find(conditions).exec();
}
module.exports = {
insert: insert,
update: update,
find: find
}
//schema.js
var mongoose = require('./db.js'),
Schema = mongoose.Schema;
var LagouSchema = new Schema({
name: {type: String},
cid: {type: Number},
process: {type: String},
content: {type: String},
url: {type: String},
tag: {type: String},
total: {type: Number},
salary: {type: Array}
});
var Lagou = mongoose.model('lagou', LagouSchema, 'lagou');
function update(conditions, update){
Lagou.update(conditions, update, function(err, res){
if(err) console.log('Error:' + err);
else console.log('Res:' + res);
})
}
function del(conditions){
Lagou.remove(conditions, function(err, res){
if(err) console.log('Error:' + err);
else console.log('Res:' + res);
})
}
function find(conditions, callback){
Lagou.find(conditions, function(err, res){
if(err) console.log('Error:' + err);
else callback(res);
})
}
module.exports = {
find: find,
del: del,
update: update
}
//db.js
var mongoose = require('mongoose'),
DB_URL = 'mongodb://localhost:27017/result';
mongoose.Promise = global.Promise;
mongoose.connect(DB_URL);
//连接成功
mongoose.connection.on('connected', function(){
console.log('Mongoose connection open to ' + DB_URL);
})
//连接异常
mongoose.connection.on('error', function(err){
console.log('Mongoose connection error: ' + err);
})
//连接断开
mongoose.connection.on('disconnected', function(){
console.log('Mongoose connection disconnected');
})
module.exports = mongoose;
============更新2017-01-12===================
尝试设置了--max_old_space_size还是报错
报错内容:
$ node --max_old_space_size=2000 models/test.js
Mongoose connection open to mongodb://localhost:27017/result
<--- Last few GCs --->
251717 ms: Mark-sweep 1989.2 (2067.0) -> 1989.3 (2067.0) MB, 1564.0 / 0 ms [allocation failure] [scavenge might not succeed].
253271 ms: Mark-sweep 1989.3 (2067.0) -> 1989.2 (2067.0) MB, 1554.2 / 0 ms [allocation failure] [scavenge might not succeed].
254868 ms: Mark-sweep 1989.2 (2067.0) -> 1989.3 (2067.0) MB, 1597.0 / 0 ms [last resort gc].
256434 ms: Mark-sweep 1989.3 (2067.0) -> 1989.2 (2067.0) MB, 1566.2 / 0 ms [last resort gc].
<--- JS stacktrace --->
==== JS stack trace =========================================
Security context: 00000394003B4639 <JS Object>
2: /* anonymous */(aka /* anonymous */) [D:\software\self_learn\Paper\preprocess\node_modules\mongodb-core\lib\connection\pool.js:~1096] [
pc=000002BA3DA6C022] (this=00000394003041B9 <undefined>)
3: waitForAuth(aka waitForAuth) [D:\software\self_learn\Paper\preprocess\node_modules\mongodb-core\lib\connection\pool.js:1088] [pc=000002
BA41DE1FBC] (this=00000394003041B9 <undefined>,cb=0000...
FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory
ringa_lee2017-04-17 15:55:18
이 오류는 mongodb와는 관련이 없는 것으로 보입니다. 노드 프로그램의 메모리 문제입니다
이것을 시도해 볼 수 있나요?
node --max_old_space_size=2000 server.js
심각한 오류: CALL_AND_RETRY_LAST 할당 실패 - 프로세스 메모리 부족
巴扎黑2017-04-17 15:55:18
우선 데이터베이스에 보이는 데이터의 크기는 프로그램이 메모리에 읽어들이는 양과 다릅니다. 데이터 양을 줄이고 문제가 있는지 확인하기 위해 몇 가지 조건을 추가하는 것이 좋습니다. 그런 다음 더 많은 데이터를 추가하여 문제가 있는지 확인하시겠습니까? 문제가 있을 때 레코드가 몇 개 있는지 확인해보세요.
둘째, 왜 기능에 문제가 있다고 생각하나요? DesData.update는 동기식 쓰기 방법을 사용하고 있습니다. 그런 다음 tag.foreach 메서드가 여러 번 반복되어야 한다는 것을 알 수 있지만 이는 상당히 커야 합니다. oom 문제입니다. 실행을 기다리는 비동기 메서드가 너무 많이 쌓여 있습니다. 그리고 이렇게 비동기적으로 작성해도 정말 괜찮을까요? 코드를 변경하려면 async 패키지를 사용하는 것이 좋습니다. forEachLimit을 사용하는 것이 가장 좋습니다. 전화로 입력하는 동안에는 코드를 직접 변경하지 않겠습니다. 내가 컴퓨터를 하고 있을 때.