从Mongoose find方法中的其他集合中获取数据

fetching data from other collections inside Mongoose find method

本文关键字:集合 获取 数据 其他 find 方法 Mongoose      更新时间:2023-09-26

我正在与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在表中都需要是唯一的,但作为另一个文档的字段,它不需要是唯一的,除非您在该字段上添加了索引。