Node mongoose将一个数组元素移动到另一个数组中

时间:2017-03-01 04:40:27

标签: arrays node.js mongodb

我目前有一个UserSchema,如下所示:

UserSchema = new mongoose.Schema({
    username: String,
    email:  String,
    password: String,
    pendingFriends: [this],
    friends: [this]
})

给定一个用户名,我如何将pendingFriends数组中的记录移动到friends数组中?这将发生在当前登录用户的架构中。这是我将朋友放入pendingFriends数组的路线:

app.post("/addFriend", function(req, res) {
var conditions = {
    username: req.body.globalUserName,
    'pendingFriends._id': {$ne: req.user._id},
    'friends._id': {$ne: req.user._id}
}
var update = {
    $addToSet: {pendingFriends: { _id: req.user._id, username: req.user.username, language: req.user.language, profilePicture: req.user.profilePicture}}
}

User.findOneAndUpdate(conditions, update, function(error, doc) {
    if(error) {
        console.log(currentTime + " - FRIEND_REQUEST_SEND_ERROR: '" + req.user.username + "' TRIED TO SEND A FRIEND REQUEST TO '" + req.body.globalUserName + "'");
    }
    else {
        console.log(currentTime + " - FRIEND_REQUEST_SENT: '" + req.user.username + "' SENT A FRIEND REQUEST TO '" + req.body.globalUserName + "'");
    }
    res.redirect("/talk");
});

});

1 个答案:

答案 0 :(得分:0)

我认为以下代码会有所帮助

var conditions = {
username: req.body.globalUserName,
'pendingFriends._id': {$eq: req.user._id},
'friends._id': {$ne: req.user._id}
}
var update = {
   $pop: {pendingFriends: { _id: req.user._id, username: req.user.username, language: req.user.language, profilePicture: req.user.profilePicture}},
    $addToSet: {friends: { _id: req.user._id, username: req.user.username, language: req.user.language, profilePicture: req.user.profilePicture}}
}

将其用于findandupdate查询,如上所述。