可以从猫鼬的文档中获取模型吗? [英] Is it possible to get the model from the document in mongoose?
问题描述
var UserSchema = new Schema({...}); // Schema
var User = mongoose.Model('User', UserSchema); // Model
var user = new User({...}); // Document
仅提供文档(在这种情况下为用户),是否有一种简单的方法来获取模型(在这种情况下为用户),而无需事先了解文档所引用的模型是什么?有一个user.schema,但据我所知,没有user.model.
given just the document (user in this case), is there an easy way to get the model (User in this case) without prior knowledge about what model the document refers to? There's a user.schema, but as far as I can tell, no user.model.
为上下文提供了一个文档和一个路径,我想告诉数据库中是否存在该路径具有相同值的其他对象.
The context is given a document and a path, I want to tell if there are other objects with an equal value for that path in the DB.
谢谢.
推荐答案
假设您有一个user
变量,它是User模型的一个实例,但这将适用于任何猫鼬模型实例var Model = user.constructor;
,现在您可以Model.find()
运行您的查询,这将适用于任何集合.
Assume you have a user
variable that is an instance of the User model, but this will work for any mongoose model instance var Model = user.constructor;
now you can do Model.find()
to run your query and this will work on any collection.
如果需要模型名称,可以通过user.constructor.modelName
进行访问.
If you need the name of the model, it can be accessed via user.constructor.modelName
.
这篇关于可以从猫鼬的文档中获取模型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!