fun joker
fun joker

Reputation: 1727

How to insert and update existing data in database using nodejs?

I have created message schema and conversation schema. I am not able to understand why I am not able to store the data inside mongodb.

messageschema.js:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

// Create Schema
const MessageSchema = new Schema({
  author: {
    type: String,
    required: true,
  },
  message: {
    type: String,
    required: true
  },
  date: {
    type: Date,
    default: Date.now
  }
});

module.exports = mongoose.model('Message', MessageSchema);

conversationschema.js:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

// Create Schema
const ConversationSchema = new Schema({
  user1: {
    type: String,
    required: true
  },
  user2: {
    type: String,
    required: true
  },
  conversations : [{ type: Schema.Types.ObjectId, ref: 'Message' }]

});

module.exports = mongoose.model('Conversation', ConversationSchema);

server.js:

let db = mongoose.connection;
var user1, user2;

db.once('open', function() {
  console.log("Database is now connected");

  let io =  socket(server);

io.on("connection", function(socket){
  console.log("Socket Connection Established with ID :"+ socket.id)

  socket.on('disconnect', function(){
    console.log('User Disconnected');
  });

  let chat = db.collection('chat');
  let conversation = db.collection('conversation'); 

      socket.on('GET_USER', function (data) {
        console.log(data);
         user1 = data.user2;
      });

      socket.on('LOGGEDIN_USER', function(data) {
        console.log(data);
         user2 = data.user1;
      });

      socket.on('SEND_MESSAGE', function(data){

        let author = data.author;
        let message = data.message;
        let date = data.date;

        // Check for name and message
        if(author !== '' || message !== '' || date !== ''){
            // Insert message
            chat.insert({author:author, message: message, date:date}, function(){
              io.emit('RECEIVE_MESSAGE', [data]);
            });

            conversation.findOneAndUpdate(
              { user1 : user1, user2: user2 }, 
              { conversations : { $push : { author, message, date } } },
              { upsert : true}
            );

        }
      });

In server.js I want to add messages inside conversation (conversation is an array) and user1 and user2 (user1,user2 are string) inside conversation collection. So if the conversation is not created between user1 and user2 then create new one and store it in collection. If the previous chat is present i.e messages exist in conversation then just push the messages inside conversation array. I have implemented it in above server.js but documents are not getting inserted inside conversation collection. Documents are getting addded only chat collection.

Upvotes: 0

Views: 1413

Answers (2)

Yash Fatnani
Yash Fatnani

Reputation: 91

You can try like this below $push : { conservations : <<jsonObject.>>}

Example

 conversation.findOneAndUpdate(
        { user1 : user1, user2: user2 }, 
        { $push : {conversations : { author : 'author',message : 'message',date : 'date' }}},
        { upsert : true}
    );

Upvotes: 0

KarelG
KarelG

Reputation: 5244

You are using the findOneAndUpdate function incorrectly. The second argument is not correct. Please check the mongoDB docs (db.collection.findOneAndUpdate) to read how to use it correctly. There, you can find

Parameter: update Type: document
Description: The modifications to apply. Use Update Operators such as $set, $unset, or $rename. Using the update() pattern of field: value for the update parameter throws an error.

conversation.findOneAndUpdate(
    { user1 : user1, user2: user2 }, 
    { conversations : { $push : { author, message, date } } }, // <<---- not OK
    { upsert : true}
);

You need to use $set at the second argument:

{ $set: <your object> }

Upvotes: 2

Related Questions