Reputation: 35
How to move object from one collection to other ? What is the easiest and safest way to do it? I was trying with that:
app.post('/doneList/:id',function(req, res){
var id = mongojs.ObjectId(req.params.id);
var oneTodo;
db.todoList.findOne({_id: id},function(err,docs){
db.doneList.insert(docs,function(err,doc){
res.json(doc);
});
});
db.todoList.remove({_id: id});
});
but it crashes when I try it.
Upvotes: 1
Views: 982
Reputation: 50416
You generally need to work "inside" the callbacks, but .findAndModify()
is probably a lot cleaner here as well:
app.post('/doneList/:id',function(req, res){
var id = mongojs.ObjectId(req.params.id);
var oneTodo;
db.todoList.findAndModify(
{
"query": { "_id": id },
"remove": true
},
function(err,doc) {
if (doc) {
db.doneList.insert(doc,function(err,doc){
// respond moved
});
} else {
// respond was not found
}
);
That way the document is "removed" from the collection at the same time as the content is retrieved. Of course you only .insert()
when an actual document was matched and "inside" the callback from the initial .findAndModify()
operation.
It's one less call to the database and one less level of nesting.
Upvotes: 2
Reputation: 8340
UPDATE: Nevermind this answer. Go with Blakes Seven's answer, its better.
It crashes because you are removing before you could insert within the callback.
Give this a shot:
app.post('/doneList/:id',function(req, res){
var id = mongojs.ObjectId(req.params.id);
var oneTodo;
db.todoList.findOne({_id: id},function(err,docs){
db.doneList.insert(docs,function(err,doc){
res.json(doc);
db.todoList.remove({_id: id});
});
});
});
Upvotes: 1