You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET开发者转MEAN栈:API中Model数据访问代码导入问题求助

Fixing the getUsers Import Error & Implementing .NET-Style Separation of Concerns

Hey there! As a fellow .NET dev diving into MEAN stack, I totally get wanting to keep that clean separation between data access and request handling. Let's fix your issue and align your code with that familiar MVC pattern.

First, Let's Diagnose the Problem

Your current setup has two main issues:

  1. The getUsers function isn't being exported correctly from your model.
  2. Your model's callback usage is incorrect (you're returning data instead of passing it to the callback, which won't work for async database operations).

Step 1: Fix the User Model (Data Access Layer)

We'll make sure the model properly exports both the User schema and the getUsers method, and correct the callback flow to handle async operations properly.

const mongoose = require('mongoose');

// Define your UserSchema (add your actual fields here)
const UserSchema = new mongoose.Schema({
  username: { type: String, required: true },
  email: { type: String, required: true, unique: true }
});

// Create the User model
const User = mongoose.model('User', UserSchema);

// Implement getUsers with proper callback handling
User.getUsers = function(callback) {
  User.find()
    .exec((err, list_users) => {
      if (err) {
        // Pass the error to the callback
        return callback(err);
      }
      // Pass null for error, then the user data
      callback(null, list_users);
    });
};

// Export the User model (which now includes the getUsers method)
module.exports = User;

Step 2: Correctly Import the Model in Your Controller

Make sure you're importing the User model correctly in your controller, then use the getUsers method as intended.

// Import the User model (adjust the path to match your project structure)
const User = require('../models/user');

exports.user_list = function(req, res, next) {
  User.getUsers((err, list_users) => {
    if (err) {
      // Pass errors to Express's error handler
      return next(err);
    }
    // Send the user data as JSON
    res.json({ user_list: list_users });
  });
};

Bonus: Modernize with Async/Await (More Like .NET Async)

If you prefer a cleaner syntax that mirrors .NET's async/await pattern, you can rewrite the code like this:

Updated User Model

// Replace the getUsers method with an async function
User.getUsers = async function() {
  try {
    const list_users = await User.find().exec();
    return list_users;
  } catch (err) {
    throw err; // Let the controller handle the error
  }
};

Updated Controller

exports.user_list = async function(req, res, next) {
  try {
    const list_users = await User.getUsers();
    res.json({ user_list: list_users });
  } catch (err) {
    next(err); // Pass errors to Express's error middleware
  }
};

Why This Works

  • Separation of Concerns: Just like in .NET, your controller only handles HTTP requests/responses, while the model takes care of all database interactions.
  • Proper Async Handling: Both callback and async/await approaches correctly handle the asynchronous nature of MongoDB operations, ensuring data is passed where it needs to go.
  • Clean Exports: The model exports the full User object with attached data access methods, making it easy to import and use in your controller.

内容的提问来源于stack exchange,提问作者Vivek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:46:32