我遇到了問題,而我無法從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
請顯示您的編輯代碼。我仍然在那裏看到一個「拒絕」,所以我不確定你是編輯了問題還是粘貼了真實的代碼。並且檢查你的輸入以確保你輸入了你認爲正在輸入的內容。 –