我对学生集合有一个聚合查询,它返回两组结果 对于这样的每个学生
{ _id: 1543,
name: 'Bill Jackson',
scores: { type: 'homework', score: 38.86823689842918 } }
{ _id: 1543,
name: 'Bill Jackson',
scores: { type: 'homework', score: 15.861613903793295 } }
这很好用。现在在回调中我想删除每个学生的一个分数。我使用下面丑陋的嵌套条件来隔离我要删除的两个记录中的哪一个,并且,一旦实现了,我创建了一个查找和修改查询来删除文档,但没有证据表明它已经运行。 findAndModify的错误或成功回调都没有运行,但是我能够记录我在调用findAndModify的区域内。
是否可以在回调中查询数据库中的数据库?如果没有,我应该如何执行在db中持续存在的操作?
//aggregation query ommitted
, function(err, result) { //callbackstarts here with result of aggregation query that returns two records for each student
for (var i=0; i<result.length; i++) {
var id = result[i]['_id'];
if (id === result[i]['_id']){
if (foo && foo === result[i]['_id']){
//if we're in here, we know we need to remove score associated with this result[i]['_id']
//create findAndModify to remove the record
var query = { '_id' : result[i]['_id']}
var sort = []
var operation = { '$pull' : { 'scores.score' : result[i]['scores']['score'] } };
var options = []
console.log('this code is getting called but findAndModify not')
db.collection('students').findAndModify(query, sort, operation, options,function(err, doc) {
if(err) throw err;
if (!doc) {
console.log("record not found");
}
else {
console.log("changed doc" + doc);
}
});
}else {
var foo = result[i]['_id'] //part of logic to isolate which of two records to remove
}