将对象推送到mongoose数组并检查数组对象内的重复字段

时间:2015-12-21 17:08:55

标签: javascript node.js mongodb mongoose

我正在尝试将通知对象推送到具有以下条件的mongoDB数组:

检查阵列中是否有相同postId的通知 如果是:返回该对象 如果否:创建新的通知对象

我正在使用Mongoose ODM节点。在网上的其他一些问题中,他们给出了答案:

user.update({'notifications.postId': {$ne: post._id}}, {$push: { 'notifications': {type: 'POST', postId: post._id}}}, function(err, doc) {
  .....
});

但这对我不起作用。

下面是mongodb文档的结构。

{
    "_id": {
        "$oid": "56631b22067ee41847dab6bb"
    },
    "unreadNotifications": 0,
    "notifications": [
      {
        "type": "POST",
        "postId": {
          "$oid": "5666b78b61eb95bc03d47a71"
        },
        "_id": {
          "$oid": "56782daa395840efd4ed3f7a"
        },
        "createdAt": {
          "$date": "2015-12-21T16:49:46.903Z"
        },
        "events": []
      }    
    ]
    "created": {
        "$date": "2015-12-05T17:13:06.782Z"
    },
    "lastName": "Power",
    "firstName": "John",
    "__v": 0
}

1 个答案:

答案 0 :(得分:1)

请注意,Schema#update方法不会更新记录,因为没有指定匹配条件描述的匹配记录。

无论如何,您可以在用户架构上创建自己的方法。

实施例

UserSchema.method('sendNotification', function (post, done) {
    var notification = null;

    for (var i = 0, len = this.notifications.length ; i < len ; i++) {
        notification = this.notifications[i];
        if (notification.postId.equals(post._id)) {
            return done(null, notification);
        }
    }

    notification = {
        type: 'POST',
        postId: post._id
    };

    this.update({
        $push: {
            notifications: notification
        }
    }, function (e, doc) {
        if (e) { return done(e); }
        return done(null, notification);
    });
});

您可以在创建模型后使用此方法。

User.findOne({
    email: 'john@example.com'
}).exec(function (e, john) {
    john.sendNotification(post, function (e, notification) {
        if (e) { console.log('Ah snap! There are an error.'); }
        console.log('notification: ', notification);
    });
});