将对象推送到一个mongoosearrays,并检查数组对象内的重复字段

我试图按照以下条件推送一个通知对象到一个mongoDB数组:

使用相同的postId检查数组内是否有通知如果是:返回该对象如果否:创build一个新的通知对象

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

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

但这不适合我。

下面你可以findmongodb文档的结构。

 { "_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 } 

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

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

 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); }); }); 

创build模型后,可以使用此方法。

 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); }); });