node.js - Mongoose-如何引用嵌入文档元素?

标签 node.js mongodb mongoose

我有 users.js 架构,其中包含嵌入文档数组 pets。对于每个用户,一个用户可以拥有多个宠物(我认为通常不超过 3 个)。

对于每只宠物,都会有一个每日图表。所以对于一只宠物来说会有很多每日图表。我读过嵌入式文档,每个数组元素都有索引。在 daily.js 中,如何为 populate() 函数引用它所属的宠物?

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var userSchema = new Schema({
    firstName: { type: String, required: true },
    lastName: { type: String, required: true },
    username: { type: String, required: true, unique: true },
    location: String,
    pets: [{ name: 'string', animalType: 'string'}], //could have more than one pet
    created_at: Date,
    updated_at: Date
});

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var dailySchema = new Schema({
  tite: String,
  _pet: { type: Number, ref: 'User.pet' }, // not sure how to reference name in user.pets[#] array
  created_at: Date,
  updated_at: Date
});

最佳答案

Quoting

Sorry to disappoint but that is an anti-pattern. Populate can't populate from another collection's subdocs - the reason why you're getting that error is that there's no model for boards.

因此,引用嵌入文档可能不是一个好的模式。最好将 petUser 分离为一个架构

var PetSchema = new Schema ({ 
    name: 'string', 
    animalType: 'string'
});

UserSchemaDailySchema 将是

var userSchema = new Schema({
    ...
    pets: [{ type: Schema.Types.ObjectId, ref: 'Pet' }], //could have more than one pet
});

var dailySchema = new Schema({
  _pet: { type: Number, ref: 'Pet' }, // not sure how to reference name in user.pets[#] array
});

关于node.js - Mongoose-如何引用嵌入文档元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34822320/

相关文章:

node.js - 更新 mongo 中的对象数组

javascript - 更新 mongo 文档数组中单个子文档的计数

javascript - 这是查询 MongoDB 的最佳结构吗?

node.js - 填写依赖版本号的npm命令是什么?

node.js - 请求发射器在 Express 中未发出 'end'

node.js - 我想在heroku 中托管一个聊天应用程序(Socketio、Node)。需要使用人群生成

mongodb - 从 Google Compute Engine 远程连接 mongo

c# - 聚合后的 MongoDb 计数 C# 2.0 驱动程序

node.js - 前端只能访问后端 - 您如何解决此类问题?

node.js - 如何防止 mongodb 支持的分布式 Nodejs Web 服务器架构中的竞争条件