2016-02-18 3 views
0

У меня есть две схемы Mongoose, User и Code. У каждого пользователя может быть много кодов.Вложенные документы в Mongoose

user.js:

var mongoose = require('mongoose'); 
var codeSchema = require('./code'); 
var userSchema = mongoose.Schema({ 
    google: { 
     id: String, 
     token: String, 
     email: String, 
     name: String 
    }, 

    codes: [codeSchema] 
}, {collection : 'users'}); 

code.js:

var mongoose = require('mongoose'); 
var codeSchema = mongoose.Schema({ 
    code: String, 
    name: String, 
    link: String 
}, {collection: 'codes'}); 

module.exports = codeSchema; 

Моя проблема заключается в том, когда я достигаю массив пользователя кодов по user.codes, я получаю что-то вроде { _id: 56c4c82a37273dc2b756a0ce },{ _id: 56c4c82a37273dc2b756a0cd }, а не JSON для кода.

Что мне не хватает?

+1

Почему вы не добавляете индексированное поле 'userId' в' codes'? Затем вы можете найти все коды из этой коллекции с помощью 'userId' –

ответ

0

Woops, оказывается, я использовал неправильный набор данных, не добавляя коды правильно (FACEPALM). Спасибо всем, кто ответил!

0

Вам не хватает populate.

По умолчанию Mongoose предоставит вам только ссылки на любые ссылки, сделанные в документе. populate позволяет заполнять вложенные документы.

userSchema.findOne({}).populate('codes');

Более here

0
please check that you are inserting other values or not this can be a case . Please write how you are inserting in array . I have two other way check out 

There are two way to do this 
1-->either you save refrence id of codeschema and 
2--> is you can insert whole codeschema in array 

1. codes: { 
     type: mongooseSchema.ObjectId, 
     ref: 'codeSchema', 
     required: true 
    }, 

and when all data is in array 56c4c82a37273dc2b756a0ce,56c4c82a37273dc2b756a0cd 

that can be done by this query 
domain.User.update({_id:id} 
       ,{$addToSet:{code:codeObjvalue}}, 
       function(err,res){}); 

and then populate them by this 
domain.users.find({},'code') 
       .populate('code','code color email'). 
       exec(function(err,results){ 
     callback(err, results); 
    }); 


2-- and second is to insert whole code schema in userschema 


create a codeschema object and add in set like this 
var codeobj={}; 
codeobj.code="xyz"; 
codeobj.email="[email protected]" 
var codeobject = new domain.code(codeobj); 
    domain.User.update({_id:id},{$addToSet:{code:codeobject}},function(err,user1){ 
    });