我在我的 node.js 应用程序中使用 Mongoose 对数据库中的两个集合进行建模,它将读取和写入。还有两个集合只能从我的应用程序中读取(这些集合的模型正在另一个应用程序中维护,它将写入它们)。
如果我需要使用 mongoose 访问这两个只读集合,那么我还必须在这个应用程序中维护一个架构。我宁愿不这样做,因为架构将被维护两次,以后可能会导致不一致。
Mongoose 中的默认连接可以通过以下方式创建
Mongoose.connect(dbPath)
给定一个 dbPath(例如 mongodb://localhost/dbname
),我如何使用 Mongoose 默认连接从我的应用程序未维护架构/模型的集合中读取?还是我必须使用 native MongoDB 驱动程序?
最佳答案
如果您只是使用 Mongoose 从集合中读取数据,则可以将架构定义留空。
因此,如果您有一个名为 test
的只读集合,则可以使用以下方法:
var Test = mongoose.model('Test', new Schema(), 'test');
Test.findOne({name: 'John'}, function(err, doc) { ... });
或者为了更好的性能,包括lean()
如果您不需要任何模型实例功能,请在查询链中:
Test.findOne({name: 'John'}).lean().exec(function(err, doc) { ... });
如果您不使用 lean()
,则需要使用 get
访问文档的属性。方法;例如:
doc.get('name') // instead of doc.name
关于node.js - Mongoose 只读,没有架构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28630865/