填充Mongoose上的Schema

问题描述 投票:0回答:2

我有两个集合,一个是用户,另一个是猫。我想在我的用户集合下的猫数据。但我没有得到。

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”:“[email protected]”,“password”“$ 2a $ 10 $ ogerY6OiCRKy9TjPYERaOugUJeqelBl.yToJ4ZBX3ac2MVZQpsKOu”,“role”:“user” “,”“猫”:[],“__ v”:0

预期产出

“_id”:ObjectId(“5a446ab43533970b8489e1ac”),“username”:“xyz”,“email”:“[email protected]”,“password”“$ 2a $ 10 $ ogerY6OiCRKy9TjPYERaOugUJeqelBl.yToJ4ZBX3ac2MVZQpsKOu”,“role”:“user” “,”“cats”:[{“_ id”:ObjectId(“5a44707effc66a234447c36b”),“fname”:“felix”,“mname”:“”,“lname”:“”,}],“__ v”:0

node.js mongodb angular mongoose
2个回答
0
投票

您可以将它们组合成一个如下所示的模式。没有任何理由单独创建模式,除非数组计数连续增加数百个..

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;

0
投票

修复你的架构(应该是cats: [{ type: Schema.Types.ObjectId, ref: 'Cat' }]并参考http://mongoosejs.com/docs/populate.html

© www.soinside.com 2019 - 2024. All rights reserved.