猫鼬只读,无模式 [英] Mongoose read-only without schema

查看:61
本文介绍了猫鼬只读,无模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的node.js应用程序中使用Mongoose建模数据库中的两个集合,它将对它们进行读写.还有另外两个集合只能从我的应用程序读取(这些集合的模型将在另一个应用程序中维护,它将写入其中).

I am using Mongoose in my node.js app to model two collections in the database, which it will read and write. There are two more collections which are going to be read only from my app (the model for these collections is being maintained in another app, which will write to them).

如果我需要使用猫鼬访问两个只读集合,那么我也将必须在此应用程序内维护一个架构.我宁愿不这样做,因为该架构将被维护两次,并可能在以后导致不一致.

If I need to access the two read-only collections using mongoose, then I will have to maintain a schema within this app as well. I would rather not do this as the schema will be maintained twice and could lead to inconsistency later on.

猫鼬的默认连接可以通过

The default connection in Mongoose can be created by

Mongoose.connect(dbPath)

给出一个dbPath(例如mongodb://localhost/dbname),如何使用Mongoose默认连接从其应用程序未维护其架构/模型的集合中进行读取?还是我必须使用原生的MongoDB驱动程序?

Given a dbPath (e.g. mongodb://localhost/dbname), how can I use the Mongoose default connection to read from a collection whose schema/model is not being maintained by my app? Or will I have to use the native MongoDB driver for the same?

推荐答案

如果您仅使用Mongoose从集合中读取内容,则可以将模式定义保留为空.

If you're just using Mongoose to read from a collection, you can leave the schema definition empty.

因此,如果您有一个名为test的只读集合,则将可以执行以下操作:

So if you had a read-only collection named test, something like this will work:

var Test = mongoose.model('Test', new Schema(), 'test');
Test.findOne({name: 'John'}, function(err, doc) { ... });

或者为了获得更好的性能,如果您的查询链中包含 lean() 您不需要任何模型实例功能:

Or for better performance, include lean() in your query chain if you don't need any of the model instance functionality:

Test.findOne({name: 'John'}).lean().exec(function(err, doc) { ... });

如果您不使用lean(),则需要使用

If you don't use lean() you need to access the properties of the doc using the get method; for example:

doc.get('name') // instead of doc.name

这篇关于猫鼬只读,无模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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