【问题标题】:Javascript's find() function not working for array embedded documentsJavascript find() 函数不适用于数组嵌入文档
【发布时间】:2022-01-17 15:02:47
【问题描述】:

我正在尝试为博客文章构建赞成/反对票功能,无论用户之前是否点击过按钮都是必需的。但 javascript find() 功能不起作用。有没有办法从数组中获取匹配的嵌入文档?

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);

【问题讨论】:

    标签: javascript node.js mongodb sockets mongoose


    【解决方案1】:

    发现解决方案“===”不适用于文档并适用于.equals

    【讨论】:

      猜你喜欢
      • 2011-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-08
      • 2015-12-02
      相关资源
      最近更新 更多