Mongoose中的嵌套文档

时间:2016-02-18 19:32:48

标签: node.js mongodb mongoose

我有两个Mongoose模式,User和Code。每个用户都可以有很多代码。

user.js的:

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

module.exports = codeSchema;

code.js:

user.codes

我的问题是,每当我通过{ _id: 56c4c82a37273dc2b756a0ce },{ _id: 56c4c82a37273dc2b756a0cd }访问用户的代码数组时,我会得到{{1}}而不是代码的JSON。

我错过了什么?

3 个答案:

答案 0 :(得分:0)

你错过了populate

默认情况下,Mongoose只会为您提供文档中所做引用的_id。 populate允许您填写嵌套文档。

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

更多here

答案 1 :(得分: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="xyz@gmail.com"
var codeobject = new domain.code(codeobj);
    domain.User.update({_id:id},{$addToSet:{code:codeobject}},function(err,user1){
    });

答案 2 :(得分:0)

Woops,结果我使用了错误的数据集,没有正确添加代码(facepalm)。感谢所有回答的人!