填充Mongoose上的Schema

时间:2017-12-28 04:28:24

标签: node.js mongodb angular mongoose

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

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”,          “密码” “$ 2A $ 10 $ ogerY6OiCRKy9TjPYERaOugUJeqelBl.yToJ4ZBX3ac2MVZQpsKOu”           “角色”:“用户”,           “猫” : [ ],           “__v”:0

预期产出

  

“_ id”:ObjectId(“5a446ab43533970b8489e1ac”),           “username”:“xyz”,           “email”:“xyz@gmail.com”,          “密码” “$ 2A $ 10 $ ogerY6OiCRKy9TjPYERaOugUJeqelBl.yToJ4ZBX3ac2MVZQpsKOu”           “角色”:“用户”,            “猫” : [{           “_id”:ObjectId(“5a44707effc66a234447c36b”),           “fname”:“felix”,           “mname”:“”,           “lname”:“”,            }],           “__v”:0

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分:0)

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