Egg: 请教:关于egg-mongoose使用的两个问题

Created on 1 Apr 2017  ·  10Comments  ·  Source: eggjs/egg

  • Node Version: 7.8.0
  • Egg Version: 1.0.0
  • Plugin Name: egg-mongoose
  • Plugin Version: 1.1.1
  • Platform: macOS


在用egg-mongoose的时,遇到了两个问题:

一个是,如何将一个schema中的一个属性类型设置为另外一个schema类型,例如:

const PostSchema = new mongoose.Schema({
    // 标题
    title: {
      type: String,
      required: true,
      unique: false,
    },
    // 阅读者
    readers: [ UserSchema ],
....

上面的写法在运行时会直接报错。在egg中应该如何编写此类代码?

另外一个问题是,通过下面的代码,

const users = this.ctx.model.user.find({});

可以获取mongodb中的Users集合中的数据,那保存用egg-mongoose是如何写法的呢?

egg-mongoose

Most helpful comment

对了, @feidianbo ,mongoose需要new一下才保存的,e.g.

const userModel = new this.ctx.model.user(body)
userModel.save()...

All 10 comments

我这两天尝试下来直接使用Models可以
而在Schemas加方法不行

保存是 model.xxx.save().then()

另外一个schema类型,是指的关联吗?

var Schema = app.mongoose.Schema;
var ObjectId = Schema.Types.ObjectId;

var backupSchema = new mongoose.Schema({
    user_id: {
      type: ObjectId,
      ref: 'User'  //关联User这个schema
    }, 
});

@jtyjty99999

this.ctx.model.user.save()...

像上面写保存数据时提示 this.ctx.model.user.save is not a function。

另外,如何将数据赋值到user对象中。

多谢。

有个疑问,app/model/下的文件怎么使用service里的方法?

对了, @feidianbo ,mongoose需要new一下才保存的,e.g.

const userModel = new this.ctx.model.user(body)
userModel.save()...

app/model/下的文件怎么使用service里的方法,有人解决吗

app/model 不应该使用 service.

这个 issue 还有什么问题么?

@jtyjty99999 有create方法吗?

我在 app/model 下遇到一种情况可能需要使用到 service
数据库使用 egg-mongoose,需要使用 mongoose middleware,在 pre save 的时候进行一系列的数据更新操作

  schema.pre('save', async function(){
    await service.xx.method()
  })

我觉得mongoose就相当于service的作用了,就没必要service了,感觉这里有点不清晰

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Quekie picture Quekie  ·  3Comments

yuu2lee4 picture yuu2lee4  ·  3Comments

lvgg3271 picture lvgg3271  ·  3Comments

aka99 picture aka99  ·  3Comments

popomore picture popomore  ·  3Comments