从Mongoose find方法中的其他集合中获取数据
fetching data from other collections inside Mongoose find method
我正在与Node.js和mongoose(mongodb)合作的应用程序。除了model population
之外,是否有任何方法可以从查找方法中的其他集合中获取信息?population
与_id
一起工作,我在另一个集合中的id不能重复,也不能有一对多的关系。
例如,每个用户都有不止一本图书。在图书模式中,_id
应该是重复的,并且其中一堆具有相同的用户id。但我不想这样。我想比较一下其他领域。
我在Mongoose文档中阅读document#population
,但我无法理解:http://mongoosejs.com/docs/api.html document_Document-populate
我真不敢相信,为了这个简单的需求,Mongoose竟然没有一个好的api。
这是我的模式:
var mongoose = require('mongoose');
var Users = require('../users');
var schema = new mongoose.Schema({
book_name: String,
book_publisher: String
});
var book = mongoose.model('book', schema);
module.exports = book;
和
var mongoose = require('mongoose');
var Book = require('../book');
var Schema = mongoose.Schema;
var schema = new mongoose.Schema({
user_name: String,
books: [{ type: Schema.Types.ObjectId, ref: 'Book' }]
});
var users = mongoose.model('users', schema);
module.exports = users;
本质上,问题不在于猫鼬,而在于猫鼬。您要做的基本上是在非关系数据库中提取关系数据。根据经验,我建议不要这样做。如果无法避免,请使用postgres。Postgres支持json数据
在mongoose中,您可以使用.populate方法加载第一级关系(users -> posts)。如果希望引入第二级关系(用户->帖子->回复),那么最终需要在代码中手动创建连接。因此,如果用户有多本书,您可以这样设置模式。
User = new mongoose.Schema({
//existing user properties
owned_books: [{type: mongoose.Schema.Types.ObjectId, ref: 'book'}]
}}
//now you can query users and populate their books by doing
Users.find().populate('owned_books').exec(callback)
编辑:也可以反过来,书有一群用户。在任何情况下,_id在表中都需要是唯一的,但作为另一个文档的字段,它不需要是唯一的,除非您在该字段上添加了索引。
相关文章:
- 如何使用backbone.js从集合中获取模型名称
- 主干-从模板中迭代的集合中获取特定的模型
- 获取Href的集合
- 尝试从集合中获取特定模型
- Backbone集合:如何从API中获取特定对象以放置在模型中
- 如何获取jQuery集合中的第k个元素..作为JQUERY元素
- 所需响应的主干无限集合获取调用
- Backbonejs最简单的集合获取
- 主干.js:仅添加来自 JSON 集合获取的新模型
- 我无法使用 lodash _.template 从一个主干视图中的多个集合获取数据
- Backbone.js集合获取'这个_byId'未定义
- 使用特定的ajax调用设置集合获取
- 在 Backbone 中使用相同类型的集合获取不同的模型集
- 使用主干集合获取数据子集
- 主干集合获取选项不影响GET请求
- 从backbone.js集合获取model.id使用Tastypie创建成功调用
- Onchange集合获取错误而不是函数
- 主干集合获取抛出id错误
- 从mongodb集合获取所有文档时出错
- 从服务器上的Meteor集合获取项目会抛出“;可以't wait without Fiber”;