The array does not store the ObjectId

I'm trying to implement the favoriting feature following a tutorial, but I'm encountering issues with making it work. Any assistance would be greatly appreciated. Thank you!

UserSchema:

var UserSchema = new mongoose.Schema({
    username: {type: String, lowercase: true, unique: true, required: [true, "cannot be blank"], match: [/^[a-zA-Z0-9_]+$/, 'is invalid'], index: true},
    email: {type: String, lowercase: true, unique: true, required: [true, "cannot be blank"], match: [/\S+@\S+\.\S+/, 'is invalid'], index: true},
    bio: String,
    image: String,
    hash: String,
    salt: String,
    following: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User' }],
    favorites: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Article' }]
}, {timestamps: true});

User favorite article method:

UserSchema.methods.favorite = function(id){
    if(this.favorites.indexOf(id) === -1){
      console.log("id is: ", id) //
      this.favorites.concat(id);
    }
    console.log("this favorites is:", this.favorites);
    return this.save();
};

Post request to mark an article as a favorite:

router.post('/:article/favorite', auth.required, function(req, res, next) {
  var articleId = req.article._id;

  User.findById(req.payload.id).then(function(user){
    if (!user) { return res.sendStatus(401); }

    return user.favorite(articleId).then(function(){
      return req.article.updateFavoriteCount().then(function(article){
        return res.json({article: article.toJSONFor(user)});
      });
    });
  }).catch(next);
});

Curl request example:

curl --location --request POST 'http://localhost:3000/api/articles/how-to-train-your-dragon-m06dim/favorite' \
--header 'Content-Type: application/json' \
--header 'X-Requested-With: XMLHttpRequest' \
--header 'Authorization: Token eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVlOTIxMTQ3ZWYxZjkxMzcwZjEwMDkwNiIsInVzZXJuYW1lIjoidGl5YXl1IiwiZXhwIjoxNTkyMDIzODMxLCJpYXQiOjE1ODY4Mzk4MzF9.pIA7RVgVbRI6-2IQzW2vptEzwiZrqCroz8-SdGRNEF8' \
--data-raw ''

In the server logs, it shows that the user's favorites list remains empty even after marking an article as a favorite:

Listening on port 3000
Mongoose: users.ensureIndex({ username: 1 }) { unique: true, background: true }
Mongoose: articles.ensureIndex({ slug: 1 }) { unique: true, background: true }
Mongoose: users.ensureIndex({ email: 1 }) { unique: true, background: true }
Mongoose: articles.findOne({ slug: 'how-to-train-your-dragon-m06dim' }) { fields: undefined }
Mongoose: users.find({ _id: { '$in': [ { inspect: [Function: inspect] } ] }}) { fields: undefined }
Mongoose: users.findOne({ _id: { inspect: [Function: inspect] } }) { fields: undefined }
id is:  ObjectID { _bsontype: 'ObjectID', id: '^•C\u0006’ï`w2%\u0014f' }
this favorites is: []
Mongoose: users.count({ '$and': [ { username: 'tiyayu' }, { _id: { '$ne': { inspect: [Function: inspect] } } } ]}) {}
Mongoose: users.count({ '$and': [ { email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="55213c2c342c20152c342c347b363a38">[email protected]</a>' }, { _id: { '$ne': { inspect: [Function: inspect] } } } ]}) {}
Mongoose: users.update({ _id: { inspect: [Function: inspect] } }) { '$set': { updatedAt: { inspect: [Function: inspect] } } }
Mongoose: users.count({ favorites: { '$in': [ { inspect: [Function: inspect] } ] }}) {}
Mongoose: articles.count({ '$and': [ { slug: 'how-to-train-your-dragon-m06dim' }, { _id: { '$ne': { inspect: [Function: inspect] } } } ]}) {}
Mongoose: articles.update({ _id: { inspect: [Function: inspect] } }) { '$set': { updatedAt: { inspect: [Function: inspect] } } }
POST /api/articles/how-to-train-your-dragon-m06dim/favorite 200 126.823 ms - 423

Answer №1

Shoutout to @Joe for coming in clutch with the solution:

I had a lightbulb moment when I realized I needed to swap out the outdated push method for the concat method, but I didn't execute it correctly:

myArray.push(myObject); //causing issues on DocumentDB with Mongo API due to deprecated $pushAll

The correct way to handle this was something like:

myArray = myArray.concat([myObject]);

Therefore, my revised method now looks like this:

UserSchema.methods.favorite = function(id){
    if(this.favorites.indexOf(id) === -1){
      this.favorites = this.favorites.concat([id]);
    }
    return this.save();
};

Big thanks once again for your assistance Joe!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A guide to finding matching data in two collections with mongoose's aggregate method

My quiz application has two schemas: const quizSchema = new mongoose.Schema({ userID: { type: String, required: [true, 'User ID required'] } }); Response Schema - const responseSchema = new mongoose.Schema({ userID: { type: Str ...

Is there a way for me to replace zero with a different number dynamically?

Is there a way to dynamically insert a different number instead of zero in mongoose? displayCity: (req, res, next) => { let id = req.params.id; provinceAndCity.findById({ _id: id }).populate('city.0.limitation', 'title ...

What are the steps to implement the jQuery slide menu effect on a website?

When visiting the website , you may notice a symbol positioned in the top left corner of the site. By clicking on this symbol, a sleek div will slide out. How can this type of animation be achieved through javascript or jquery? ...

React video recording not displaying in the video element

I'm currently developing a React application that facilitates webcam interviews with candidates. As part of this process, candidates have the option to "Start Again" or "Complete" their interviews. One challenge I am facing is displaying the recorded ...

Struggling to display array components from a MongoDB record using express-edge templating

I am currently working through a blog tutorial to learn backend development using nodejs and mongodb. The tutorial seems a bit outdated as I have had to make some tweaks to get things to work properly. However, I am not following the tutorial exactly. Inst ...

Is Node.js going to continue to provide support for its previous versions of node modules?

I currently have a website that relies on the following dependencies. While everything is working smoothly at the moment, I can't help but wonder about the future support of these packages by node.js. I've looked into the legacy documentation of ...

Unpacking JSON Objects in Typescript: Working with Private Variables

I have a TypeScript model object called user export class User { constructor( private _name: string, private _email: string ) {} public get name():string { return this._name; } public set name(value:string) { this._name = value; } g ...

Preventing Angular $rootElement.on('click') from affecting ReactJS anchor tag interactions

Running both AngularJS and ReactJS on the same page has caused an issue for me. Whenever I click on a ReactJS <a> tag, Angular's $rootElement.on('click) event is triggered and the page redirects. I need to perform some functionality in Re ...

How to eliminate a hyperlink from an HTML element with the help of JQuery

Recently, I was assigned to revamp a website for the company I work for. However, upon closer inspection, I realized that the website is quite messy and relies heavily on templates, resulting in certain elements being auto-generated as active links. The i ...

Guide to incorporating Moengage into Node.js APIs for delivering email notifications based on user interactions

How can Moengage be integrated into Node Js APIs for sending notifications to users based on user events? I have reviewed the Moengage API documentation but did not find relevant information on integrating Moengage with Node Js APIs. Is there a step-by-s ...

Forwarding based on URL/Query Parameters

I'm looking to create a redirect for users based on URL or query parameters, but I'm not sure how to go about it. For example, if the URL is https://www.tamoghnak.tk/redirect?link=https://www.tamoghnak.tk/gobob, I want to redirect to /gobob. If ...

Tips for utilizing the getJson method to pass a variable to a PHP file

I need help with my JavaScript code, as I am trying to pass a datastring containing the value "no" to data.php using getJson in order to receive JSON as a response. However, my JavaScript code is not functioning correctly. Below is the code that I have: J ...

Using Vue along with bootstrap-vue: Ensuring only one list element is expanded in a list (v-for) at any given time

In my Vue project with bootstrap-vue, I am utilizing the b-collapse feature within a v-for loop for lists. While it is functioning correctly, I am struggling to automatically close expanded list elements when a new one is clicked. Here is my question: Ho ...

No data returned from API call in Next.js and Strapi

Recently, I encountered an issue with my Next.js frontend application that fetches data from a Strapi backend. Despite seeing requests being made in the Strapi developer logs, the retrieved data is empty. Below is a snippet of my Next.js code: import { us ...

Troubleshooting VueJS, Electron, and Webpack integration with Hot Reload feature

I have been immersed in a new project that involves utilizing Electron, VueJS, and Webpack for HMR functionality. Unfortunately, I am encountering difficulties with the Hot Module Replacement feature not working as expected. Here is my current configurati ...

Executing npm commands programmatically from a node.js script

Currently, I am developing a specialized command line interface (CLI) for managing various packages to be installed or uninstalled using npm. Should I execute npm through spawn('npm') or require('npm')? require('child_process&apos ...

Issues with Loading Bootstrap JavaScript on Basic "Hello World" Project

I am experiencing an issue where the JavaScript code is not displaying on my website. I have checked the inspect element sources and it seems to load correctly, but for some reason, it is not being applied. Any insights on why this might be happening? Than ...

What methods can I utilize to increase the speed of my JavaScript animation?

Recently, I implemented a Vue component designed to loop a div over the X axis. While it functions correctly, I can't help but notice that it is consuming an excessive amount of CPU. I am interested in optimizing this animation for better performance. ...

Having trouble accessing the req.body value in a Node ExpressJS server while using server-sent events?

I've been attempting to transmit a payload from my SSE client to an SSE node server. Despite receiving sse.js on my React client in order to send the payload back to the server, I keep encountering a JSON error. The error message reads: SyntaxError: ...

stop tabs from being visible during window reload

I am currently working on a page that features 4 jQuery UI tabs. The first tab simply displays a greeting message saying "HELLO". The 2nd, 3rd, and 4th tabs contain HTML and PHP scripts that are functioning correctly. However, when I execute the PHP script ...