如何在架构阵列中发布和更新架构并打印它?

时间:2016-05-03 10:15:03

标签: node.js mongodb mongoose schema populate

您好我是节点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;

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

当我通过邮递员发布用户时,用户正在添加,但我没有得到完整的类型,我不知道它是否保存正确

这是json i post

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

这是get users json

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

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

希望我足够清楚

感谢帮助者

1 个答案:

答案 0 :(得分:1)

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

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

当您阅读数据时,Mongoose群体通过其 populate() 功能非常简单地读取文档。例如,要显示特定用户的引用类型,请使用字符串中该字段的名称作为参数调用 populate() 方法,例如

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