Home > Software engineering >  Javascript's find() function not working for array embedded documents
Javascript's find() function not working for array embedded documents

Time:12-19

I am trying to build an upvote/downvote functionality for blog posts, whether a user clicked a button or not previously is needed. but the javascript find() function is not working. Is there any way to get the matched embedded documents from array?

index.js

io.on( 'connection', function( socket ) {
console.log( 'a user has connected!' );

socket.on( 'disconnect', function() {
    console.log( 'user disconnected' );
});

socket.on( 'upvote-event', async function( upvote_flag , id) {
    console.log(typeof id);  //getting the post id from button click
    console.log(user.upvotes_downvotes); //upvote downvote array
    const post_Id = new ObjectID(id);
    const PreClicked = user.upvotes_downvotes.find(clicked => {
        console.log(clicked.postId,post_Id)
        return clicked.postId === post_Id; // where it is failing
    });
    var ok = false;
    console.log(PreClicked, post_Id); //PreClicked is always undefined :( 
    if(PreClicked === undefined)
    {
        upvote_count = 1;
        const newUpvote = { postId: post_Id, types: "upvote" };
       // console.log(user._id);
        await User.findOneAndUpdate({_id: user._id},
            { $push: 
                { 
                    upvotes_downvotes: newUpvote
              },
            },
        )
        
    }else if(PreClicked.types==="upvote"){ //Never goes here even if the upvoted posts exists in array
        upvote_count = -1;
       await User.findOneAndUpdate({_id: user._id},
        { $pull:
             { upvotes_downvotes:{
                  
                $elemMatch:{ 
                        postId: post_Id, types: "upvote" 
                    }
                }
             } 
        })
    }
 });

schema.js

const  Mongoose  = require('mongoose');
const Schema = Mongoose.Schema;
const passportLocalMongoose = require('passport-local-mongoose');

User  =  new Schema({
email : {
    type : String,
    required : true,
    unique : true
},
upvotes_downvotes:[{
    postId:{ type: Schema.Types.ObjectId , ref:'Post'},
    types: String
     }],

  });

 module.exports = Mongoose.model('User',User);

CodePudding user response:

Found the solution "===" is not applicable for documents and worked for .equals

  • Related