我正在關注這篇文章以在 AdonisJS 5 專案中使用 Mongo。
我有一個由我創建的 AdonisJS 提供程式node ace make:provider Mongo(它在 中注冊.adonisrc.json):
import { ApplicationContract } from '@ioc:Adonis/Core/Application'
import { Mongoose } from 'mongoose'
export default class MongoProvider {
constructor(protected app: ApplicationContract) {}
public async register() {
// Register your own bindings
const mongoose = new Mongoose()
// Connect the instance to DB
await mongoose.connect('mongodb://docker_mongo:27017/mydb')
// Attach it to IOC container as singleton
this.app.container.singleton('Mongoose', () => mongoose)
}
public async boot() {
// All bindings are ready, feel free to use them
}
public async ready() {
// App is ready
}
public async shutdown() {
// Cleanup, since app is going down
// Going to take the Mongoose singleton from container
// and call disconnect() on it
// which tells Mongoose to gracefully disconnect from MongoBD server
await this.app.container.use('Mongoose').disconnect()
}
}
我的模型是:
import { Schema, model } from '@ioc:Mongoose'
// Document interface
interface User {
email: string
}
// Schema
export default model(
'User',
new Schema<User>({
email: String,
})
)
控制器:
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import User from 'App/Models/User'
export default class UsersController {
public async index({}: HttpContextContract) {
// Create a cat with random name
const cat = new User({
email: Math.random().toString(36).substring(7),
})
// Save cat to DB
await cat.save()
// Return list of all saved cats
const cats = await User.find()
// Return all the cats (including the new one)
return cats
}
}
它正在超時。
它正在作業,當我像這樣在控制器中打開連接時:
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import User from 'App/Models/User'
import mongoose from 'mongoose'
export default class UsersController {
public async index({}: HttpContextContract) {
await mongoose.connect('mongodb://docker_mongo:27017/mydb')
// Create a cat with random name
const cat = new User({
email: Math.random().toString(36).substring(7),
})
// Save cat to DB
await cat.save()
// Return list of all saved cats
const cats = await User.find()
// Close the connection
await mongoose.connection.close()
// Return all the cats (including the new one)
return cats
}
}
我剛剛創建了一個 AdonisJS 提供程式,在 .adonisrc.json 中注冊了它,創建了一個帶有型別的合同/Mongoose.ts,并在控制器中使用了模型。
任何的想法?我被困了一天。
謝謝
uj5u.com熱心網友回復:
如果有人感興趣:
在文章作者的幫助下,Mongoose創建模型時它不作業的原因丟失了(Mongoose.model而不僅僅是model:
export default Mongoose.model(
'User',
new Schema<User>({
email: String,
})
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/368209.html
上一篇:聚合在貓鼬中沒有按預期作業
