mercredi 25 février 2015

Mongo won't save the right relation / _id

I'm trying to parse data from an array into a mongodb database, where we find a table Thread and Post. The table Threads has an object posts which should store the posts as a mongoose.Schema.Types.ObjectId . Now the problem ist that the _id of the posts are being saved to the according Thread, but later on when trying to populate('posts') the returned array is [].


Here there is the code that updates the Threads and inserts the Posts



function savePosts(posts, thread){


posts is the response of a RESTful api call in JSON, thread is a Thread object which was queried from the database earlier on an is passed through the functions



now = new Date();
Thread.update({_id: thread._id}, {last_parsed: now}, function(err, post){
if(err){ return console.log(err); }
});

for(i=0; i<posts.length; i++){

var post = new Post({no: posts[i].no, body: posts[i].body, attachement: posts[i].attachement,time: posts[i].time*1000, thread: thread._id});
var upsertData = post.toObject();
delete upsertData._id;


At this point the Post is not saved with post.save() because one thread can be parsed plenty of times and every post should only be saved once (according to it's posts.no)



Post.findOneAndUpdate({no: posts[i].no}, upsertData, {upsert: true}, function(err, uPost){
if(err){ console.log(err); return; }
thread.posts.push(uPost);
});
}

Thread.update({_id: thread._id}, {posts: thread.posts}, function(err, uThread){
if(err){ return console.log(err); }
console.log('Thread filled with Posts: '+uThread);
});

}

Aucun commentaire:

Enregistrer un commentaire