问题描述
我有一个包含两个用户的对话模式.我想标记要从一个用户删除的邮件,以便其他收件人仍可以阅读该邮件.
I have a conversation schema which will contain two users. I want to flag messages to be deleted from one user so the other recipient still able to read the message.
架构
// Messages Schema
var messagesSchema = new Schema({
from: {
type: Schema.Types.ObjectId,
required: true,
ref: 'User',
},
content: {
type: String,
required: true,
trim: true
},
deleted_by: [{
type: Schema.Types.ObjectId,
ref: 'User'
}],
read_by: [{
type: Schema.Types.ObjectId,
ref: 'User'
}],
}, {
timestamps: true
});
// Conversation Schema
var conversationsSchema = new Schema({
recipients: [{
type: Schema.Types.ObjectId,
required: true,
ref: 'User',
index: true
}],
messages: [messagesSchema],
}, {
timestamps: true
});
现在,当我在两个用户之间创建对话时,它将类似于以下内容
Now when I create a conversation between two users it will look like the following
[
{
"_id": "57bb6fed3d001f054e809175",
"updatedAt": "2016-08-22T21:37:30.631Z",
"createdAt": "2016-08-22T21:34:37.381Z",
"__v": 2,
"messages": [
{
"updatedAt": "2016-08-22T21:34:37.380Z",
"createdAt": "2016-08-22T21:34:37.380Z",
"from": "57b7448668d04d3035774b9a",
"content": "Hello are you there?",
"_id": "57bb6fed3d001f054e809176",
"read_by": [],
"deleted_by": []
},
{
"updatedAt": "2016-08-22T21:34:58.060Z",
"createdAt": "2016-08-22T21:34:58.060Z",
"from": "57b7448668d04d3035774b9a",
"content": "I miss you",
"_id": "57bb70023d001f054e809177",
"read_by": [],
"deleted_by": []
},
{
"updatedAt": "2016-08-22T21:37:30.631Z",
"createdAt": "2016-08-22T21:37:30.631Z",
"from": "57b7816b68d04d3035774b9b",
"content": "Hey... Me too",
"_id": "57bb709a3d001f054e809178",
"read_by": [],
"deleted_by": []
}
],
"recipients": [
"57b7448668d04d3035774b9a",
"57b7816b68d04d3035774b9b"
]
}
]
现在,当其中一个用户想要从他的身边删除对话时,我想将用户ID添加到每条消息内的deleted_by
数组中.
Now when one of the users want to delete the conversation from his side I want to add the user id to the deleted_by
array inside each message.
我正在尝试做这样的事情
I am trying to do something like this
Conversation.findOneAndUpdate({
_id: conversation_id
}, {
$push: {
'messages.deleted_by': req.loggedInUser._id
}
}, function(err, data) {
if(err) return next(err);
res.json(data);
})
返回错误
TypeError: Cannot read property '$isMongooseDocumentArray' of undefined
我试图添加$
符号,但仍然遇到相同的错误.
I tried to add the $
sign and still getting the same error.
推荐答案
尝试一下:
Conversation.findOne({
_id: conversation_id
}, function(err, docs) {
if(err) return next(err);
if(docs)
{
docs.messages.forEach(function(msg,index,array)
{
msg.deleted_by.push(req.loggedInUser._id);
});
docs.save();
}
});
阅读此以取得更好的效果了解forEach函数.
Read this for better understanding of forEach function.
我希望这会有所帮助.
这篇关于使用$ push更新猫鼬子文档中的多个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!