简体   繁体   中英

How do i display my data from MongoDB Atlas in my node js application?

I am trying to display data from sample collection thats in mongoDB Atlas. i have connected to the server, retrieved the data. But the problem is i cannot choose specific data. if i do it says undefined .

Here is the pic and code for better understanding:

MY MOVIE MODEL movie.js

const mongoose = require("mongoose");
const { Schema } = mongoose;
require("dotenv").config();

const mongoDB_API = process.env.MONGODB_API_KEY;

const mflixDB = mongoose.createConnection(mongoDB_API).useDb("sample_mflix");

const Movies = mflixDB.model("Movie", new Schema({}), "movies");
module.exports = Movies;

I used the code via mongoose access preexisting collection

Snippet of MongoDB ATLAS: mongoDB 代码段

my app.js

const express = require('express');
const bodyParser = require('body-parser');
const _ =require('lodash');
const mongoose = require('mongoose');

require('dotenv').config();

const app = express();
app.set("view engine","ejs");
app.use(bodyParser.urlencoded({extended:true}));
app.use(express.static('public'));


const Movies = require('./model/mflix/movies');

app.get("/movies",async (req, res) => {
    const ourMovies = await Movies.find().sort({'date': -1}).limit(2);
    console.log("WE recieved: \n")
    console.log(ourMovies);
    const titles =[];
    ourMovies.forEach( x=>{
         console.log(x._id, x.title)
    })
    res.render("movies", { recievedList: ourMovies });
  });

the output: 此代码的输出

As u can see x.title is undefined instead of respective title.

I cannot access any info other than _id. Is this because i didn't properly defined my schema for the model ? How do i fix this?

I was browsing more on this answer( this link ) and decided to try other ways to do similar thing

Solution from this: Solution , i tried that soliton and added it in my code in following manner:

in app.js

const express = require('express');
const bodyParser = require('body-parser');
const _ =require('lodash');
const mongoose = require('mongoose');

require('dotenv').config();

const app = express();
app.set("view engine","ejs");
app.use(bodyParser.urlencoded({extended:true}));
app.use(express.static('public'));

//we dont really need this (UNUSED)
const Movies = require('./model/mflix/movies');

const mongoDB_API = process.env.MONGODB_API_KEY;

const mflixDB = mongoose.createConnection(mongoDB_API).useDb("sample_mflix");

app.get("/movies", async (req, res) => {
  const collection = mflixDB.collection("movies");
  collection
    .find({})
    .limit(2)
    .toArray(function (err, data) {
      console.log("\nour data:");
      console.log(data); // it will print your collection data
        data.forEach(x=>{
            console.log(`Id: ${x._id} \t title: ${x.title}`)
        })
    });

  const ourMovies = await Movies.find().sort({ date: -1 }).limit(2);
  // console.log("WE recieved: \n")
  // console.log(ourMovies);
  // const titles =[];
  // ourMovies.forEach( x=>{
  //      console.log(x._id, x.title)
  // })
  res.render("movies", { recievedList: ourMovies });
});

The output:It shows title (and not undefined like above question) 在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM