Javascript 将对象推送到mongoose数组,并检查数组对象中是否存在重复字段
我尝试将通知对象推送到mongoDB阵列,条件如下: 检查阵列中是否存在具有相同postId的通知 如果是:返回该对象 如果否:创建新的通知对象 我在Mongoose ODM中使用node。在其他一些在线问题中,他们给出以下回答:Javascript 将对象推送到mongoose数组,并检查数组对象中是否存在重复字段,javascript,node.js,mongodb,mongoose,Javascript,Node.js,Mongodb,Mongoose,我尝试将通知对象推送到mongoDB阵列,条件如下: 检查阵列中是否存在具有相同postId的通知 如果是:返回该对象 如果否:创建新的通知对象 我在Mongoose ODM中使用node。在其他一些在线问题中,他们给出以下回答: user.update({'notifications.postId': {$ne: post._id}}, {$push: { 'notifications': {type: 'POST', postId: post._id}}}, function(err, do
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
}
请注意,Schema#update
方法不会更新记录,因为指定的匹配条件没有描述匹配的记录
无论如何,您可以在用户模式上创建自己的方法
例子
这对@DavidGrinbergNot没有帮助。我不确定你所做的事情在一个小时内是可能的query@BobS您可以更新您的问题以包含您的模式吗?这是弄清楚为什么你正在尝试的东西不起作用的关键。你可以试试这个问题中给出的答案
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);
});
});