/    Sign up×
Bounties /Pin to ProfileBookmark

findById() mongoose method not working properly

I’m trying to use the findById method in mongoose, and I keep getting a null object from my console.log

import mongoose from "mongoose";

const idNum = '5a68fe2142ae6a6482c4c9cb';

mongoose.connect('mongodb://localhost/mongo-exercises')
.then(()=> console.log('Connected to MongoDB...'))
.catch(err=>console.error('Could not connect...'));

const courseSchema = mongoose.Schema({
    tags: [ String ],
    date: { type: Date, default: Date.now },
    name: String,
    author: String,
    isPublished: Boolean,
    price: Number
});

const Course = mongoose.model('Course', courseSchema);

async function showCourse(){
    const course = await Course.findById(idNum).exec;
    console.log(course);
};
to post a answer
Back-endNode.js

2 Replies

Davinci•003 auto-replyIt sounds like you're having trouble with the findById() mongoose method. It's possible that the issue is related to the way you're passing in the id parameter. Make sure that the id is being passed in as a string and not an object. If that doesn't work, you may need to check the mongoose documentation to see if there are any other parameters that need to be passed in.

const findById = async (id) => {
try {
const result = await Model.findById(id);
return result;
} catch (err) {
console.log(err);
return null;
}
};

Was this helpful?

Copy linkTweet thisAlerts:
@SempervivumMar 16.2023(updated) — Apparently connection to the DB is working asynchronously. Try to do it all in an async function: import mongoose from "mongoose"; const idNum = '5a68fe2142ae6a6482c4c9cb'; async function doIt() { await mongoose.connect('mongodb://localhost/mongo-exercises') .then(() => console.log('Connected to MongoDB...')) .catch(err => console.error('Could not connect...')); const courseSchema = mongoose.Schema({ tags: [String], date: { type: Date, default: Date.now }, name: String, author: String, isPublished: Boolean, price: Number }); const Course = mongoose.model('Course', courseSchema); const course = await Course.findById(idNum).exec; console.log(course); } doIt();
×

Success!

Help @dev-craig spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.19,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...