【问题标题】:Populating Sub documents according to userid根据 userid 填充 Sub 文档
【发布时间】:2018-07-10 01:40:39
【问题描述】:

我正在开发 MEAN 应用程序。我正在尝试为每个登录的用户管理单独的数据。我需要在我的主集合 user 下填充子集合。

user.js

var mongoose = require("mongoose");
var userSchema = new mongoose.Schema({
username: String,
email: { type: String, unique: true, lowercase: true, trim: true },
password: String,
role: String,
pwd_token: String
});
var User = mongoose.model('User', userSchema);
 exports.default = User;

cat.js

var mongoose = require("mongoose");
var catSchema = new mongoose.Schema({
name: String,
breed: String,
colour: String
});
var Cat = mongoose.model('Cat', catSchema);
exports.default = Cat;

如何根据 userid 用我的用户填充子集合?

【问题讨论】:

  • 来自CAT 模型你想填充?
  • 兄弟,我的用户收藏下需要猫
  • Cat 将在您的用户集合中,并且您将从您希望填充 cat 的用户那里查询。 ?
  • 正是我需要的兄弟
  • 添加了一个答案,检查一次

标签: node.js angular mongodb mongoose


【解决方案1】:

比如说,在 User [User.js] 模型中有一个字段,名为 cat_id,其中包含 Cat _id。这是Cat模型的参考。

var mongoose = require("mongoose");
    var userSchema = new mongoose.Schema({
    username: String,
    email: { type: String, unique: true, lowercase: true, trim: true },
    password: String,
    role: String,
    pwd_token: String,
    cat_id:{
      type:mongoose.Schema.Types.ObjectId,
      ref:"Cat" //Reference Of Cat Model otf Type ObjectId
    }
    });
    var User = mongoose.model('User', userSchema);
     exports.default = User;

现在,如果当您从 Cat 进行查询时,只需执行 populate("user_id") 以填充与 user_id 相关的用户文档

示例查询: 此查询将为您提供所有 User Docs 。并在其中填充相关的Cat doc。

User.find({}).populate("cat_id").exec()

这里是doc .populate()

【讨论】:

  • 我已经完成了这个 var userSchema = new mongoose.Schema({ username: String, email: { type: String, unique: true, lowercase: true, trim: true }, password: String, role : String, pwd_token: String, cat_id: { type: mongoose.Schema.Types.ObjectId, ref: "Cat" //引用猫模型otf Type ObjectId } }); var User = mongoose.model('User', userSchema); User.find({}).populate("cat_id").exec();出口。默认 = 用户;但它没有填充猫
  • 确保cat_idCat 集合文档中的任何_id 匹配。
  • 你的意思是 user_id 应该在 Cat 中?
  • 不,cat_id [in User] 应该是来自Cat 的有效_id
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-08-06
  • 2017-04-21
  • 2017-01-27
  • 2021-02-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多