简体   繁体   中英

Populate Schema on Mongoose

I have two collections one is users and another is cats. I want cats data under my users collection. But I am not getting.

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

Expected Output

"_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

You might combine them into just one schema like below. No any reason to create schemas separately unless the array count increases a couple of hundreds continuously..

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;

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

You can get data like this, using model.find().populate('ref')

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

It will return all the users and against each user, an array of respective Cat . You already mentioned the ref of the Cat in the User model , so you don't need to do anything extra.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM