Answer the question
In order to leave comments, you need to log in
What is the correct way to access an array in Mongoose?
There is a message schema that stores all messages from users.
Each user has an array of dialogs (correspondences), each of which stores message ids. The diagram looks like this:
dialogues: [{
name: mongoose.Schema.Types.ObjectId, // contain order id
messages: [{
id: {
type: mongoose.Schema.Types.ObjectId
}, // contain message id
properties: {
hidden: {
type: Boolean,
default: false
},
new: {
type: Boolean,
default: true
}
}
}]
}]
function insertUserMessages(userId, dialogTitle, message) {
User.findById(userId, function(err, user) {
User.update(
{dialogues: { $elemMatch: { name: dialogTitle } } },
{ $push: { "dialogues.messages": message } },
{ safe: true, upsert: true },
function(err, result) {
if (err) console.log(err);
}
);
});
}
Answer the question
In order to leave comments, you need to log in
The solution was this: The
user's dialogs are stored in this form
"dialogues" : {
"58f9e5ff408da70504fede05" : [ // <---- человек по-переписке
{
"id" : ObjectId("590880f1c612893834123438") // <---- id сообщения, здесь могут быть дополнительные
}, // параметры. Например, скрыл ли его пользователь.
...
],
"58f9fcb6794ac63bf44bd61c" : [
{
"id" : ObjectId("5908a3470d59a45a64715bb2")
},
...
]
}
User.findByIdAndUpdate(
userId,
{$push: {['dialogues.' + message.recipient]: {id: message._id}} },
{ safe: true, upsert: true },
function(err, user) {
if (err) console.log(err);
}
);
I do not pretend to be correct, but I would make a separate collection for dialogues.
_id : mongoid,
author: userId,
recipient: userId,
message: [{
author: userId,
text: "",
timestamps: true
}]
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question