您可以在Mongoose中为子文档定义实例方法吗? [英] Can you define instance method for sub documents in Mongoose?

查看:65
本文介绍了您可以在Mongoose中为子文档定义实例方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在Mongoose中有一个定义如下的模式:

If I have a a Schema in Mongoose that's defined like:

var subSchema = new Schema({
  some: String
});

var topSchema = new Schema({
  subs: [subSchema]
});

var topModel = mongoose.model("Top", topSchema);

是否可以为子文档定义实例方法?我已经尝试了以下方法(在模型声明之前添加),但是它不起作用:

Is it possible to define an instance method for the sub document? I've tried the following(added before the model declaration), but it doesn't work:

subSchema.methods.someFn = function() { 
  return 'blah';
};

推荐答案

回答我自己的问题.

我最初想要做的是创建一个可用于子文档集合的函数,如:

What I originally wanted to do was to create a function that can be used on the collection of subdocs, as in:

topdoc.subs.someFn();

但是,我实际上在原始问题中使用的代码是为子文档本身创建一个函数,如下所示:

However, what I actually did with code in the original question was create a function for a subdoc itself, as in:

topdoc.subs[i].someFn();

这有效.

据我所知,Mongoose不支持为子文档的集合创建函数.

As far as I can tell, creating a function for the collection of subdocs is not supported by Mongoose.

我通过在topSchema中定义一个可以实现我想要的方法的方法来解决这个问题.

I got around this by defining a method in topSchema that would do what I want.

这篇关于您可以在Mongoose中为子文档定义实例方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆