mongodb 在Mongoose上填充架构

zbwhf8kr  于 2023-01-04  发布在  Go
关注(0)|答案(3)|浏览(152)

我有两个集合,一个是用户,另一个是猫。我希望猫的数据下我的用户集合。但我没有得到。
User.js

var Schema = mongoose.Schema;
var userSchema = Schema({
_id: Schema.Types.ObjectId,
username: String,
email: { type: String, unique: true, lowercase: true, trim: true },
password: String,
role: String,
cats: [{ type: Schema.ObjectId, ref: 'Cat' }]
});
var User = mongoose.model('User', userSchema);
exports.default = User;

Cat.js

var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var catSchema = Schema({
fname: String,
mname: String,
lname: String,
});
var Cat = mongoose.model('Cat', catSchema);
exports.default = Cat;

O/p
"_id" : ObjectId("5a446ab43533970b8489e1ac"), "username" : "xyz", "email" : "xyz@gmail.com", "password""$2a$10$ogerY6OiCRKy9TjPYERaOugUJeqelBl.yToJ4ZBX3ac2MVZQpsKOu", "role" : "user", "cats" : [ ], "__v" : 0
预期输出
"_id" : ObjectId("5a446ab43533970b8489e1ac"), "username" : "xyz", "email" : "xyz@gmail.com", "password""$2a$10$ogerY6OiCRKy9TjPYERaOugUJeqelBl.yToJ4ZBX3ac2MVZQpsKOu", "role" : "user", "cats" : [{ "_id" : ObjectId("5a44707effc66a234447c36b"), "fname" : "felix", "mname" : "", "lname" : "", } ], "__v" : 0

pdtvr36n

pdtvr36n1#

你可以像下面这样把它们组合成一个模式。没有任何理由分开创建模式,除非数组计数连续增加几百个。

var Schema = mongoose.Schema;
var userSchema = Schema({
  _id: Schema.Types.ObjectId,
  username: String,
  email: { type: String, unique: true, lowercase: true, trim: true },
  password: String,
  role: String,
  cats: [
    { 
      _id: Schema.Types.ObjectId,
      fname: String,
      mname: String,
      lname: String,
    }
  ]
});
var User = mongoose.model('User', userSchema);
exports.default = User;
rekjcdws

rekjcdws2#

修复您的架构(应为cats: [{ type: Schema.Types.ObjectId, ref: 'Cat' }]并引用http://mongoosejs.com/docs/populate.html

hmmo2u0o

hmmo2u0o3#

可以使用model.find().populate('ref')获得如下数据

const story = await User.find().populate('Cat');

它将返回所有用户,并针对每个用户返回各自的Cat数组。您已经在User model中提到了Catref,因此不需要执行任何额外操作。

相关问题