Leveraging two databases with Mongoose

I am trying to connect to a different database in mongoose using the following code:

const mongoose = require('mongoose');
const connectionOptions = { useCreateIndex: true, useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false };
const conn = mongoose.createConnection("mongodb://localhost/db_en", connectionOptions);

const Schema = mongoose.Schema;

const priceSchema = new Schema({

    fixed: {
        1: { type: Number, default: 199 }, 
        3: { type: Number, default: 499 }, 
        6: { type: Number, default: 729 },
        12: { type: Number, default: 999 }
    }
});

conn.model('Price', priceSchema);

Afterwards, I aim to input data into the Price model within the newly established database:

const ggg = new conn.Price();

 await ggg.save(); 

However, an error message is consistently being thrown:

TypeError: conn.Price is not a constructor

Answer №1

To access your model, make sure to assign it to an object first. Take a look at the code snippet below:

const priceSchema = new Schema({

    fixed: {
        1: { type: Number, default: 199 }, 
        3: { type: Number, default: 499 }, 
        6: { type: Number, default: 729 },
        12: { type: Number, default: 999 }
    }
});
var priceModel = mongoose.model('Price', priceSchema);
var priceObject = new priceModel();

priceObject.save(function (err, result) {
    if (err) console.log(err);
    else console.log('The following price was saved:', priceObject);
});

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

React: Implementing a Logout Functionality for Expired Cookies

Scenario: In my application, I am utilizing express-session on the backend to manage user sessions. On the frontend React part, I have implemented functionality to restrict access to protected routes for users. However, there is a tricky situation that ari ...

Preference for executing multiple dependent ajax calls synchronously

There are various approaches to handling multiple dependent ajax synchronous calls, but two of the most commonly used methods are the jQuery defer method and using callbacks on success. My inquiries include: 1) What are the benefits of utilizing one me ...

"Utilizing the $in Operator in Pymongo for Regular Expressions: A Step-by-

Can anyone assist with a MongoDB aggregation issue I'm having? I'm trying to aggregate a collection based on a specific path in the Log_Dir field, but I can't seem to get it to work with pymongo. Just a note, I am using the 'version&apo ...

Deactivate the focus state when hovering over different items in the navigation bar

Currently facing an issue with my Navbar items having underline animation on hover. Once clicked, the animation persists. However, when hovering over a neighboring navbar item, the underlines appear next to each other, creating the illusion of one long lin ...

Leveraging the power of Framer Motion in combination with Typescript

While utilizing Framer Motion with TypeScript, I found myself pondering if there is a method to ensure that variants are typesafe for improved autocomplete and reduced mistakes. Additionally, I was exploring the custom prop for handling custom data and des ...

The Node.js Express framework seems to be failing to respond to incoming requests

I am currently utilizing the express web framework and attempting to send an $http request from angularjs. Despite passing data to the server through the client, the server is not receiving the request for reasons unknown to me. Can anyone offer some assis ...

What is the reason for needing to export the function when importing a module in an Angular appModule?

I came across the following code snippet @NgModule({ declarations: [ ... ], imports: [ RoutingModule, SharedModule, JwtModule.forRoot({ config: { headerName: 'Authorization', tokenGetter: () => lo ...

Exploring the concepts of relative and absolute paths in JavaScript

I'm struggling to grasp the concept of relative and absolute paths. Can someone please help explain how they operate in relation to the directory? I have the following code but I am unable to include the PostService module. import { Component } from ...

Creating a dynamic table in HTML by parsing nested JSON data with ajax

Below is an example of the JSON data I am working with. I have been struggling to display it properly in an HTML table, as it only shows 3 columns with "undefined" values. How can I correctly access and display my JSON data? { "count": 3, "entries": [ ...

Can Vue.js be paired with pure Node.js as a backend without relying on Express?

After successfully building a project with both vue js and node js, specifically with express, I'm curious if it's feasible to solely utilize node js without frameworks like express. ...

Are the files selected by the user not displaying properly in the URL?

I'm currently working on a project using PhoneGap where I am facing an issue with uploading files and adding all file names to the parameters. The desired format is: http://www.example.com/uplaod.html?file=file1,file2,file3 To achieve this, I have a ...

The React Stripe API is functioning perfectly on local servers but encountering issues in the live environment

Just when I thought I was almost finished, reality hits me hard! My deadline is right around the corner! I finally got everything working on my local machine with a stripe payment form. However, when I pushed it live, I received an error message from my A ...

Should I store users in the admin database or the local database in MongoDB?

When setting up a MongoDB server, is there a recommended approach for where to place database users? I currently have my users in the admin database with access granted only to their respective databases. Do you think it might be more advisable to store u ...

Measuring Euler Angles with 9-Axis Analog Sensor Data

I am trying to calculate Euler angles using analog sensor data in JavaScript. The sensor data consists of gyro, accelerometer, and magnetometer readings in three dimensions. I find the mathematical aspect a bit challenging, so any assistance or advice woul ...

Is there a way to stop CSS from randomly changing rotation direction after numerous rotations in Safari?

I was tasked with creating a card element that consistently flips in the same direction when clicked. The code snippet I found achieved this perfectly, but only worked on Chrome and Firefox. However, when testing it on Safari on both iOS and MacOS, I encou ...

What is the best method for coordinating the Vue mounted function with external dependencies?

Within my Vue mounted function, I am in need of both an internal value referred to as foo and an external value known as bar. Here is a snippet from myVue.js file -- //myVue.js export var myVue = new Vue({ el: '#my-vue', data: { ...

Navigating the realm of JavaScript and managing the uncertainties of floating point precision

I am exploring the development of a browser multiplayer game utilizing rollback netcode that operates a deterministic simulation on the clients. I successfully prototyped the netcode in Flash, but encountered a floating point roadblock along the way. As f ...

What is the best way to modify a current DOM element in React?

I have been utilizing the cropper.js tool to extract screenshots from a PDF file. My goal now is to personalize the crop box tool by adding some custom buttons at the bottom of the crop box. Upon loading the PDF file, cropper.js generates certain DOM eleme ...

From organizing nested arrays in jSon to visualizing data with D3js

I am completely new to working with d3 and JSON. I have a piece of data from JSON that I am attempting to extract, and I'm wondering if I am headed in the right direction. My goal is to display a rectangle graph for each server within different statu ...

How come HTML fails to display an image sent through Express?

I have a remote server with an Express server that serves a tiger image at this link. The Express server code on the link is: var express = require('express'); var app = express(); app.use(cookieParser()) app.use(cors()) app.use(helmet()) app.us ...