[英]How can I find all results in a PHP array, merge values, and then merge into another array
[英]MongoDB: how can I find and merge array
我正在嘗試在我的文檔中找到一個特定的ID,然后將一個數組合並到現有的數組中,例如,如果我將這個數組存儲在db.friends中:
["12","13","14"]
我發送這個數組: ["12","16","18"]
,db.friends應該包含: ["12","13","14","16","18"]
我正在使用下划線庫,但我不確定是否必須(可能在mongoose中“聚合”?)
這就是我做的,你能告訴我在哪里錯了嗎?
function saveFollowers(req, res) {
var friends = req.body.friends; // the new array to merge ["54aafe9df4ee360300fc94c7"];
User.findOne({_id: req.user._id}).exec(function (err, user) {
if (err) {
res.jsonp({error: "Error fetching user info"})
} else {
friends = _.extend(friends, user.friends); //user.friends=existing friends we have in db
user.save(function (err) {
if (err) { res.jsonp({error: "Cant save"}); }
console.log("Friends NOW:"+JSON.stringify(friends)); //Here I don't see the merge, also, I can't see it in mongo db.
res.jsonp("success");
});
}
});
謝謝!
使用當前的實現,您實際上沒有修改返回的用戶對象中的friends鍵。 所以你可以使用union
方法
user.friends = _.union(friends, user.friends); //user.friends=existing friends
user.save(function (err) { .. }
或者使用ES6使用擴展運算符連接數組,使用Set創建一組不同的元素:
user.friends = [...new Set([...friends ,...user.friends])];
user.save(function (err) { .. }
另一種方法是使用聚合框架,您可以使用$setUnion
運算符:
function saveFollowers(req, res) {
var friends = req.body.friends; // the new array to merge ["54aafe9df4ee360300fc94c7"];
User.aggregate([
{ "$match": { _id: req.user._id } },
{
"$project": {
"friends": { "$setUnion": [ "$friends", friends ] }
}
}
]).exec(function (err, results){
if (err) {
res.jsonp({error: "Error fetching user info"})
} else {
User.findByIdAndUpdate(req.user._id,
{ "$set": { "friends": results[0].friends } },
{ "new": true },
function (err, user) {
if (err) { res.jsonp({error: "Cant save"}); }
console.log("Friends NOW: "+ JSON.stringify(user.friends));
res.jsonp("success");
}
);
}
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.