我的用户模型中有以下值。
"courseId" : [
"5ac37f5cd494e905b86c2433",
"5ac3861b8ef3100798036040",
"5ac42ce009092c3058893590",
"5ac47e2787f5a70428640ed3",
"5ac710fbc1c4ea39b8050c94",
"5ac3861b8ef3100798036040",
"5ac3861b8ef3100798036040",
"5acc4b59336cfc3de4b05e69",
"5acc4b59336cfc3de4b05e69"
],
如您所见,最后两个值是重复值。我试图通过这个mongoose查询更新它们:
User.update({ "_id": req.params.userid }, { $set: { courseId: User.distinct("courseId", { "_id": req.params.userid }) } }, function (err) {
if (err) {
console.log(err);
} else {
console.log("distinct done");
}
});
在这里,我可以向您保证该功能正在req.params
中接收用户ID,但它不会删除重复值。我做错了什么?
答案 0 :(得分:0)
distinct
将异步执行。您需要在回调中调用update
User.distinct("courseId", { "_id": req.params.userid }, function(err, courseIds){
//handle err
User.update({ "_id": req.params.userid }, { $set: { courseId: courseIds } },
function (err) {
if (err) {
console.log(err);
} else {
console.log("distinct done");
}
});
});