首先,这是我的文件:
{
"_id" : "Members",
"Member_Index" : [
"wCwam8zqotSSMeyDwOfEfmMhZFn2",
"wpbcaIFEMeds3HmM2JOmIz05RGq1",
"imbb0r1aOhMzFnHCDWKBiLhSTr03",
"mzle6EjxNHVIrySiVo90ftyK2jC3",
"j8xP1GzeEIRM0Oq07g7b1vgSpPv1"
],
"Classes" : [
{
"date" : ISODate("2017-08-30T05:00:21.437Z"),
"className" : "Run",
"_id" : "1504069221437",
"registeredMembers" : []
}
]}
我正在尝试将一个字符串推送(追加)到Classes.ARRAY_INDEX.registeredMembers数组中。我能用这个更新索引0:
gym.findByIdAndUpdate("Members",
{$push: {'Classes.0.registeredMembers': req.query.UID}},
{safe: true, upsert: true}, function(err, model) {
if (model != null) {
console.log('Updated with UID');
res.sendStatus(200);
} else {
console.log('Failed to update');
console.log(err);
res.status(404).send('Failed to update')
}
});
我想更改索引(我从另一个查询中知道)。我试着在field参数中传入一个连接的字符串;但是,它需要一个对象。
var param = 'Classes.' + index + '.registeredMembers';
传入上述变量代替'Classes.0.registeredMembers'会导致以下错误:
Error: Invalid atomic update value for $push.
任何提示/指示将不胜感激!如果您需要更多信息,请与我们联系。
这是完整的功能:
router.get('/register_class', function(req, res, next) {
if (!req.query.token || !req.query.UID || !req.query.GID || !req.query.EID) {
console.log('Invalid Params');
res.status(404).send('Invalid Parameters');
return null;
}
checkAuth(req.query.token, function(authed){
if (!authed) {
console.log('Invalid token passed. Permission Denied');
res.send('Unauthorized');
return;
}
});
console.log('Valid Access');
gid.findOne( {'GID': req.query.GID}).exec(function(err, GID) {
if (err) {
return res.send("Error");
} else {
if (GID == null) {
res.status(404).send('Invalid GID');
} else {
var GCOL = GID.GCOL;
var gym = require('../models/gym.js')(GCOL, randomstring.generate(32));
if (!gym) {
console.log('Invalid Collection Name');
res.status(404).send('Invalid Parameters')
return null;
}
console.log('Valid Collection');
gym.findOne( {'_id': "Members"}).exec(function(err, UID) {
if (err) {
return res.send(err);
} else {
if (UID == null) {
res.status(404).send('Invalid UID');
} else {
var classesArray = UID.Classes;
for (i = 0; i < classesArray.length; i++) {
if (classesArray[i]._id == req.query.EID) {
var where = ["Classes." + i + ".registeredMembers"];
console.log('Where: ' + where);
var queryParam = {where : req.query.UID};
gym.findByIdAndUpdate("Members",
{$push: {'Classes.0.registeredMembers': req.query.UID}},
{safe: true, upsert: true}, function(err, model) {
if (model != null) {
console.log('Updated with UID');
res.sendStatus(200);
} else {
console.log('Failed to update');
console.log(err);
res.status(404).send('Failed to update')
}
});
};
};
}
}
});
}
}
});
});
感谢Neil Lunn指出了正确的方向!
这有效:
var where = ["Classes." + i + ".registeredMembers"];
obj = { [where]: req.query.UID };
gym.findByIdAndUpdate("Members", {$push: obj},
{safe: true, upsert: true}, function(err, model) {
if (model != null) {
console.log('Updated with UID');
res.sendStatus(200);
} else {
console.log('Failed to update');
console.log(err);
res.status(404).send('Failed to update')
}
});
};