I am trying to create analyzing tool. It will read some sentence and process it and get some keyword for the day. After some time I would be doing same thing again. So every time i get it I have to save it and next time the same word comes I want to increase the count of the word by given value.
So for example I get content:{stackoverflow:2,question:5} first time I save that, next time I get content:{stackoverflow:3,answer:2} i should update the old record and the record will look something like this content:{stackoverflow:5,question:5,answer:2}.
I don't know what words are coming so i created content:Schema.Types.Mixed but $inc is allowed for only numbers.
{ [MongoError: Modifier $inc allowed for numbers only]
name: 'MongoError',
lastErrorObject:
{ err: 'Modifier $inc allowed for numbers only',
code: 10152,
n: 0,
connectionId: 77,
ok: 1 },
errmsg: 'Modifier $inc allowed for numbers only',
ok: 0 }
Any idea how to do it?
Update: My code.
for(index in wordsArray){
var word = wordsArray[index];
if(word!==topic && excludedWords.indexOf(excludedWords)===-1){
if(slotLoc[word])
++slotLoc[word];
else
slotLoc[word] = 1;
}
}
Words.findOneAndUpdate({slot:slot},{$inc:{content:slotLoc}},{upsert:true},function(err){
if(err)
console.log(err)
else
console.log("Saved Tweet");
})
Regards, Jishnu
You're pretty close, but you need to build up your $inc object's value using keys with dot notation instead of nested objects so that it looks like { 'content.foo': 1, 'content.bar': 2 }.
So update your code to something like:
var inc = {};
for(index in wordsArray){
var word = wordsArray[index];
if(word!==topic && excludedWords.indexOf(excludedWords)===-1){
var key = 'content.' + word;
if(inc[key])
++inc[key];
else
inc[key] = 1;
}
}
Words.update({slot:slot}, {$inc: inc}, {upsert:true}, function(err){
if(err)
console.log(err)
else
console.log("Saved Tweet");
});
Note that I used update instead of a findOneAndModify because you only need that when you want either the original or resulting doc returned.