res.json() returns { acknowledged: false }

Viewed 33

I am trying to update an array, nested within an object in MongoDB document, using mongoose. I have been over several similar questions, and only appeared to make a little success, then res.json return { acknowledged: false }, with no errors. The goal is to push an object into the "likes" array inside reactions object

This is the document that I'm trying to update

_id: new ObjectId("63179b818ebed9da5b433ee0"),
  thoughtText: "If Everything works out here, we're supposed to get a  notification send to another guy by whomsoever leaves a comment or a like on this post.",
  topic: 'Testing out the new notification codes for possible errors',
  username: 'anotherguy',
  userId: '63179a67849b0348e59d4338',
  category: 'Secrets',
  createdAt: 2022-09-06T19:12:01.345Z,
  reactions: [
    {
      CommentLikeCount: 0,
      mentions: 0,
      reactionBody: 'Welcome to U-annon anotherGuy, this is your official first reaction on the site',
      username: 'marryGold',
      _id: new ObjectId("63179cd18ebed9da5b433ee8"),
      reactionId: new ObjectId("63179cd18ebed9da5b433ee9"),
      createdAt: 2022-09-06T19:17:37.829Z,
      likes: []
    },

Below is the query I'm currently using to update the document using updateOne. EDIT: The schema.

// thought schema or post schema
const thoughtSchema = new Schema (
    {
      thoughtText: {
        type: String,
        required: true,
        minlength: 1,
        maxlength: 2000
      },
      topic:{
        type: String,
        required: true,
        minlength: 1,
        maxlength: 300
      },
      createdAt: {
        type: Date,
        default: Date.now,
        get: createdAtVal => moment(createdAtVal).startOf('hour').fromNow()
      },
      username: {
        type: String,
        required: true,
      },
      userId:{
        type: String,
        required: true
      },
      category: {
        type: String,
        required: true,
      },
      reactions: [reactionSchema],
      likes: [likeSchema],
      
    },
    {
        toJSON: {
            virtuals: true,
            getters: true,
        },
        id: false,
    }

The like schema is similar to the reaction schema,

//reaction schema
const reactionSchema = new Schema (
    { 
       reactionId: {
        type: Schema.Types.ObjectId,
        default: () => new Types.ObjectId(),
       },
       reactionBody: {
        type: String,
        required: true,
       },
       username: {
         type: String,
         required: true,
        },
        userId:{
          type: String,
          required: true
        },
        createdAt: {
          type: Date,
          default: Date.now,
          get: createdAtVal => moment(createdAtVal).startOf('second').fromNow()
        },
       mention: {
         type: Object,
         required: false
       },
       likes: [likeSchema],
       CommentLikeCount: {
        type: Number,
        default: 0,
      },
      mentions: {
        type: Number,
        default: 0
      }
    },
    {
        toJSON: {
            virtuals: true,
            getters: true
        },
        id: false,
    }
)

And this is the full controller function. including how I check to see if the same user already liked the comment

 //Like comments
  async likeComments(req, res){
    console.log(req.body, req.params)
    try {     
      const post = await Thought.findById(req.params.thoughtId)
      const comment = post.reactions.find(x => x.reactionId.toString() === req.params.reactionId)
      const liked = comment.likes.find(x => x.username === req.body.username)
      if(!liked){
        console.log('its open')
        const data = await post.updateOne({"reactions.[reaction]._id": req.params.reactionId}, {$addToSet:{"reactions.$.likes": req.body}}, { runValidators: true, new: true })
        console.log(data)
        res.json(data)
      }else{
        console.log('already liked')
        const data = await post.updateOne({"reactions.[reaction]._id": req.params.reactionId}, {$pull:{"reactions.$.likes": req.body}}, { runValidators: true, new: true } )
        res.json(data)
      }
    } catch (error) {
      console.log(error)
    }

I've on this for the entire day, I'd really appreciate any help that I can get.

1 Answers

In my app, users create word lists. A user can change the order of words in each list, they can also change the order of each list.

When a user creates or edits a list, the word list is updated.

If word lists have already been created, the word list will be added to the existing word lists.

If a word list has been edited (added words / removed words / word order changed) the existing word list will be updated.

If word lists have not been created yet, then a new document should be added to the database.

I found a solution, but it runs 2 findOneAndUpdate queries if a new word list is added. How can I achieve this with 1 query? Should I simplify my schema or change it so that it uses a nested object instead of an array?

Related