I want to connect to external database exist on local via server.
In other words I want to get the Price Model which is exist in local mongodb database not in my server:
const mongooseLocal = require('mongoose');
const connectionOptions = { useCreateIndex: true, useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false };
const conn = mongooseLocal.createConnection(config.MONGODB_URI_LOCAL, connectionOptions);
conn.on("error", console.error.bind(console, "connection error: "));
conn.once("open", async () => {
console.log("Connected successfully");
const priceModel = await conn.Price.findOne({}); // Price is a Model in local side and not exist in my server . it's on local...
console.log('init', priceModel);
});
The issue is although I see the "Connected successfully" log but I cann't get the data..
I see this error each time
typeErorr can not read property findOne of undefined
How can I fix this?
Since you're using mongoose your steps are:
findOne methodExample:
// Price model (price.model.ts)
const mongoose = require('mongoose');
const priceSchema = new mongoose.Schema({
name: String
});
exports.Price = mongoose.model('Price', priceSchema );
// index.ts (your file snippet)
const mongooseLocal = require('mongoose');
const { Price } = require('./price.model.ts');
const connectionOptions = { useCreateIndex: true, useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false };
const conn = mongooseLocal.createConnection(config.MONGODB_URI_LOCAL, connectionOptions);
conn.on("error", console.error.bind(console, "connection error: "));
conn.once("open", async () => {
console.log("Connected successfully");
const priceModel = await Price.findOne({});
console.log('init', priceModel);
});