我遇到了问题,而我无法从MongoDB中的集合返回任何结果。数据库的存在与收集和从Mongo CLI查询MongoDB集合返回结果一样。我总是从应用程序代码库中的find()查询中得到空结果。Koa.js,Mongo DB应用程序不会使用Mongoose返回任何结果
我的应用程序在运行时使用babel-register进行传输。
我app.js文件:
import Koa from 'koa';
import path from 'path';
import bodyParser from 'koa-bodyparser';
import serve from 'koa-static';
import mongoose from 'mongoose';
import Config from '../Config.js';
global.appRoot = path.resolve(__dirname);
const app = new Koa();
mongoose.connect(Config.mongo.url);
mongoose.connection.on('connected', (response) => {
console.log(response);
});
mongoose.connection.on('error', (err) => {
console.log(err);
});
............
能正常工作和对( '连接' ......回调正常工作,被称为
我的用户模式:
import mongoose from 'mongoose';
const Schema = mongoose.Schema;
const UserSchema = new Schema({
username: {
type: String,
required: true,
unique: true,
lowercase: true
},
password: {
type: String,
required:
true
},
email: {
type: String,
required: true,
unique: true
}
});
export default mongoose.model('user', UserSchema);
我的路线文件:
import Router from 'koa-router';
import authenticate from '../../middlewares/authenticate';
import mockCustomerService from '../../mock-services/customerService';
import AccountController from '../../controllers/accountController';
import UserModel from '../../models/UserModel';
const AccountControllerInstance = new AccountController(UserModel);
const authRouter = new Router();
/** Login function **/
authRouter.post('/login', async (ctx, next) => {
AccountControllerObject.login(ctx)
.then((response) => {
console.log(response);
});
});
正如你可以看到我注入用户模式进入AccountControllerInstance
账户控制器类
import ApiResponse from '../models/ApiResponse.js';
import ApiMessages from '../models/ApiMessages.js';
import UserProfileModel from '../models/UserProfileModel.js';
class AccountController {
constructor(userModel, token) {
this.ApiResponse = ApiResponse;
this.ApiMessages = ApiMessages;
this.UserProfileModel = UserProfileModel;
this.userModel = userModel;
this.token = token;
}
login(ctx) {
return this.userModel.find({ email: ctx.request.body.email });
}
该控制器所包含的功能登录,注册等等。正如你所看到的,用户模式是把作为构造函数中类的属性。
然后,我使用登录功能来查询Mongo实例,但我从来没有得到任何结果返回。我检查了收集中是否有正确的记录,并确保查询(本例中为电子邮件)是确切的,但仍然没有结果。
下面是mongo cli使用find查询生成的'degould-login'数据库'users'集合中记录的示例。
db.user.find({email: "[email protected]"})
结果:
{ "_id" : ObjectId("594a313a98e5b9f2f9dc9553"), "email" : "[email protected]", "username" : "james", "password" : "test" }
任何人看到这里发生了什么?
感谢
你为什么打包承诺?猫鼬方法已经返回Promises。你可以调用'.exec()'得到一个“完整的”Promise,但是它们默认都有一个'.then()'。我想你可能会发现一些工作,如果你只是返回普通方法的响应。 –
对不起,这是一个错误。我修改了函数,Mongo db仍然没有返回任何结果。 – devoncrazylegs
请显示您的编辑代码。我仍然在那里看到一个“拒绝”,所以我不确定你是编辑了问题还是粘贴了真实的代码。并且检查你的输入以确保你输入了你认为正在输入的内容。 –