Retrieving embedded documents from Mongoose collections

I am currently facing challenges in caching friends from social media in the user's document. Initially, I attempted to clear out the existing friends cache and replace it with fresh data fetched from the social media platform. However, I encountered an issue where the embedded documents needed to be unique across all users. This led to a duplicate key error as shown below:

{"name":"MongoError","err":"E11000 duplicate key error index: test-dev.users.$friends.outsideID_1  dup key: { : \"1205314313242\" }","code":11001,"n":0,"connectionId":274,"ok":1} 

It became evident that the system was unable to create a new document because a similar document already existed in another account. This prompted me to try a different approach by using OutsideFriend.find({'outsideID':{$in:friendsIDs}}) to identify and add new friends while avoiding duplicates. Unfortunately, the query did not return any documents, hinting at potential issues with centralized storage of embedded documents.

As I pondered on this dilemma, I questioned why my initial method failed if there were discrepancies in how the embedded docs were being handled. How should I proceed with handling this situation effectively? (Refer to schema below for reference)

Current Schema:

//External friend model                                                                                                                                                                                              
var OutsideFriend = new Schema({
         outsideID:{type:String, index:true, unique:true}
        ,username:String
        ,location:String
        ,avatarURL:String
});

//User model                                                                                                                                                                                                         
var User = new Schema({
        avatarURL:String
       ,mySMID:String
    //Social Media info                                                                                                                                                                                                   
        ,smID:{type:String, index:true, unique:true}
        ,tok:String
        ,tokSec:String
        ,friends:[OutsideFriend]
};

Answer №1

There are various elements to consider in your question, but if you wish to query OutsideFriend separately from User, it is recommended not to include them within the User model. Instead, store references as ObjectId and then utilize population in User when necessary for full details. Avoid premature optimization with embedded copies unless required, as this can lead to issues with consistency.

The updated structure for your User model would look like:

var User = new Schema({
    avatarURL:String
    //Social Media info
    ,smID:{type:String, index:true, unique:true}
    ,tok:String
    ,tokSec:String
    ,friends:[{type: ObjectId, ref: 'OutsideFriend'}]
};

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

Unable to fetch a new session from the selenium server due to an error

I'm currently in the process of setting up Nightwatch.js for the very first time. I am following the tutorial provided at this link: https://github.com/dwyl/learn-nightwatch Unfortunately, I have encountered a barrier and require assistance to resolv ...

What is AngularJS global data binding?

My template has a dynamic title that is inserted using the following code: <title>{{title}}</title> For each of my pages/routes, I use a different controller where I define the title like this: BackyApp.controller('HomeController', ...

How can you stop queuing animations and timeouts in jQuery?

I'm facing a seemingly simple problem that I need help with. On my website, there's a hidden div.notification bar at the top. This bar can be displayed by adding either the success or warning class to it. There are two scenarios: either a messa ...

toggle the outer div along with its corresponding inner div simultaneously

On one of my pages (let's call it "page1"), I have multiple divs, some nested within others. These divs are initially hidden and toggle on when a specific link is clicked (and off when clicked again). To view a nested div, the outer div must be opened ...

Iterating through an object using the forEach method (uncommon practice)

Greetings, I have the following object: data = { name: undefined, age: undefined, gender: undefined }; I am looking to iterate through each key and value pair in this object and perform an action. Here is my attempt: this.data.forEach((item: ...

Implementing a feature to insert a horizontal rule button in React Draft Wysiwyg

I am currently working on implementing a custom button in React Draft Wysiwyg that will allow me to add an <hr> tag to my content. Although I have followed the demos and documentation, I have encountered an issue where the custom button successfully ...

React-Native error message: Promise rejection unhandled - React child cannot be an object

I am experiencing an issue with rendering a list from an array of objects that have the structure provided below. While I have successfully handled the promise and set the data to the state, I keep encountering an error specifically with this array. The da ...

What is the best way to halt the current event handler thread's execution when another event is triggered that calls the same handler at

One of the functions in my code filters and sorts contents of a select dropdown based on input text entered by the user. The function filterSort() is triggered on each keyup event from the input field. Code $(inputTextField).keyup(function() { / ...

"I'm trying to incorporate react-datepicker into my ReScript application, but I'm struggling to

I am attempting to incorporate an external library like react-datepicker into my project. Below is the code snippet and how I am using it: module DatePicker = { @react.component @module("react-datepicker") external make: () => React.eleme ...

The value from select2 dropdown does not get populated in my article in Angular

I am attempting to link the selected value in a dropdown menu to an article, with a property that matches the type of the dropdown's data source. However, despite logging my article object, the property intended to hold the selected dropdown value app ...

Exploring the find method within a Mongoose Schema for an array of objects

My Node Application has the following Mongoose Schema var expenseSchema = new Schema({ particular : String, date : {type : Date, default: Date.now}, paid_by : String, amount : Number, month : String }); var roomSchema = new Schema({ ...

Connecting the search results page with the specific details page

Currently, I am developing a results page for my website and require assistance with linking each restaurant to a detail.php page. The project involves showcasing all the restaurants in San Francisco along with their health inspection scores, address, and ...

Tips for concealing API endpoints in a React Native Android application

I've developed a nodejs, express, and mongodb API that is currently hosted on Heroku. My next step is to utilize this API URL within my React Native Android app. Unfortunately, I'm facing an issue where the API URL could potentially be exposed to ...

Present intricate JSON data using only one ng-repeat in AngularJS

I am currently attempting to showcase all the books within a specific series. Initially, I utilized nested ng-repeat and achieved the desired outcome. However, with recent modifications to the layout requirements, I am no longer able to use nested ng-repea ...

When trying to run ionic serve, I encountered the following error: "[ERROR] ng has unexpectedly closed with an exit code of 127."

My attempt to launch an ionic app on my Mac has hit a roadblock. While running npm install for the dependencies, everything goes smoothly without any issues. However, when I try to run 'ionic serve' or 'ionic s', an error crops up: [ng] ...

upright scrolling mouse slider

In my project, I have implemented a vertical slider with mousewheel control using SwiperJS from https://swiperjs.com/. Although the slider is working perfectly fine, I am looking to fix the positions while scrolling on the page similar to the example pro ...

Enhancing a validation form with the 'onblur' event handler

Exploring the realm of JavaScript, I find myself intrigued by the concept of creating a validation form that activates upon clicking out of the input field. Implementing various techniques to integrate this feature into an existing form has been both chall ...

There was an error because the variable "items" has not been defined

Having some trouble with an AngularJS service where I am attempting to add an item to an array every 5 seconds. However, I keep encountering the error 'items is not defined' after the first dynamic addition... I've been tinkering with this ...

Why does this switch case statement fail to effectively replace the elements of the text in order to unravel this JavaScript problem?

Question I need help converting special characters to HTML entities in a string: &, <, >, " (double quote), and ' (apostrophe). My Code function convertHTML(str) { let tempArr = ['a']; let newArr = []; let regex ...

Tips for swapping out a specific string in an HTML webpage with a different string using JavaScript

For my HTML website, I am trying to replace one string with another using JavaScript. Specifically, within the nodeList "AuthorList," there is a string called "Test String" that needs to be changed to "new test." I have attempted various modifications of ...