如何 post 并更新模式数组中的模式并打印它?

how to post and update schema within schema array and print it?

你好,我是 node js 和 mongoose 的新手 我有两个方案,我想在另一个方案中有方案对象 我的计划

user.js

// grab the things we need
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var Genre = require('../Models/genre');

// create a schema
var userSchema = new Schema({
  name: { type: String, required: true, unique: true , index:true},
  email: { type: String, required: true, unique: true },
  password: { type: String, required: true },
  age: String,
  gender: String,
  genres: [{type: Schema.ObjectId, ref: Genre.Genre}] //this is the genre schema - the user can have many genres
});

// the schema is useless so far
// we need to create a model using it
var User = mongoose.model('User', userSchema);

// make this available to our users in our Node applications
module.exports = User;

也曾尝试过

genres: [{type: Schema.Type.ObjectId, ref: Genre.Genre}]
and genres: ['Genre']

和genre.js

// grab the things we need
var mongoose = require('mongoose');
var Schema = mongoose.Schema,
    ObjectId = Schema.ObjectId;

// create a schema
var genreSchema = new Schema({
  name: { type: String, required: true, unique: true, index: true },
  age: String,
  gender: String
});

// the schema is useless so far
// we need to create a model using it
var Genre = mongoose.model('Genre', genreSchema);

// make this available to our genres in our Node applications
module.exports = Genre;

首先我想知道这样做是否可行?有更好的方法吗?

当我 post 用户由 post 用户添加时,但我没有得到完整的类型,我不知道它是否保存正确

这是json我post

{
"name":"erez",
"age": "23",
"password":"erez1234",
"email":"erez@erez.com",
"gender":"Male",
"genres": ["57285fe32c3c15e40c000001"] /// what should be here? is it right?
}

这是获取用户 json

[
  {
    "_id": "572874be9b43cb4834000002",
    "name": "erez",
    "age": "23",
    "password": "yaniv1234",
    "email": "erez@beatman.com",
    "gender": "Male",
    "__v": 0,
    "genres": [
      "57285fe32c3c15e40c000001"
    ]
  }
]

如果它是对的 我如何在获取用户时发送所有类型的完整用户?

希望我说得够清楚

感谢帮手

定义引用时,ref 属性必须与模型定义中的模型名称完全匹配,否则会出错。 ref 值应该是一个字符串,而不是你做的一个对象,所以正确的方法应该是

genres: [{type: Schema.ObjectId, ref: 'Genre'}] 

当您读取数据时,Mongoose population 通过其 populate() function. So for instance, to show the referenced genres for a particular user, call the populate() 方法以字符串中该字段的名称作为参数,使读取文档变得非常简单例如

User.findOne({"name": "Tom"})
    .populate("genres")
    .exec(err, user) { ... }