Tatenda
Tatenda

Reputation: 699

Async/Await - Node - Express - Mongo

I'm working on a project that uses a node/express API and Mongo for storage. I have a function that tries to retrieve data from the storage using the code in the screenshot below. My understanding of async/await is that at the point of await, code execution will pause and proceed when the promise is resolved.

However, the data returned by the function (in the screenshot) is always null, although, the record is there in the db. [The slug is also passed correctly.]
I am starting to believe I am missing something regarding the concept of async/await. Could anyone please assist me with this? Am I doing something wrong here?

The calling function is as follows:

 async create(req, res, next) {

    debug(chalk.blue(`*** Create RSVP`));
    console.log(req.body.event); //event is defined and matches db
    
    const event = await Event.findBySlug(req.body.event);
    console.log(event); // logs null here
 }

Called function:

async function findBySlug(slug) {
    return await Model.findOne({ slug: slug })
    .populate('user')
    .populate('category')
    .exec();
}

Upvotes: 2

Views: 876

Answers (2)

kisor
kisor

Reputation: 484

updating your findBySlug method like this will be enough.

function findBySlug(slug) {
    return Model.findOne({ slug: slug })
    .populate('user')
    .populate('category')
    .exec();

}

Upvotes: 0

Mir Nawaz
Mir Nawaz

Reputation: 354

I have run your code, findBySlug should be working fine. below is sample code for you.

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const ObjectId = Schema.ObjectId;

mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost:27017/database-name', {useNewUrlParser: true});

const UserSchema = new mongoose.Schema({
    username: String
  })

const CategorySchema = new mongoose.Schema({
    name: String
  })

const PostSchema = new mongoose.Schema({
    content: String,
    author: {
      type: ObjectId,
      ref: 'User'
    },
    category: {
      type: ObjectId,
      ref: 'Category'
    }
  })

const Post = mongoose.model('Post', PostSchema, 'posts');
const User = mongoose.model('User', UserSchema, 'users');
const Category = mongoose.model('Category', CategorySchema, 'categories');

async function findBySlug() {

    return await Post.findOne({ content: "content name" })
    .populate('author')
    .populate('category')
    .exec();

}

 (async function run() {

    const event = await findBySlug();
    console.log(event); // logs not null here

 }())

Upvotes: 1

Related Questions