ojoj kolol
ojoj kolol

Reputation: 79

Nested mongodb query

I have a mongoose schema that models a user in a social network. In it i want to save an array of all the chats that a user has, a chat consists of a responent (the user a user is chatting with), and an array that represents the conversation.

var userSchema = mongoose.Schema({
    email        : String,
    chats         : [{ respondent : String, conversation : [{ message: String, author : String}]}],
});

How do i find an item in chats that contains a perticular respondent? In the item found, id like to push a message to the conversation.

Upvotes: 1

Views: 45

Answers (1)

Simran
Simran

Reputation: 2830

You haven't mention any key for inner chat. Specify like this :

var userSchema = mongoose.Schema({
        email        : String,
        chats         : [
         { respondent : String, 
          innerChat:[{ message: String, author : String}]}
       ],
    });

Query for adding document solution is:

var document={
email:"[email protected]",
chats:[{respondent:"UserName",innerChat:[{message:"hello",author:"authorName"}]}]
}
db.collection.insert(document);

Query for finding document on inner query

db.collection.find({"chats.innerChat.author":"authorName"});

Upvotes: 1

Related Questions