Mongoose findOne返回空数组字段

时间:2017-03-24 23:29:50

标签: node.js mongodb mongoose

我有一个简单的嵌入式文档:

{
    "username":"user001",
    "name":"John",
    "tasks":[
        {           
            "id":0,
            "title":"Candy",
            "description":"Lots of candy for you",
            "category":"food",
            "cost":2500,
            "candyTypes":[
                {"name":"gum", "type":"sweet", "price":"2"},
                {"name":"chocolate", "type":"tasty", "price":"3"}
            ]
        }
    ]
}

当我尝试通过mongo shell查询任务数据时,我得到了所有内容:

db.users.findOne({ 'username': 'user001', 'tasks.id':4 }, {'tasks.$':1})

/* returns */

"tasks":[
    {           
        "id":0,
        "title":"Candy",
        "description":"Lots of candy for you",
        "category":"food",
        "cost":2500,
        "candyTypes":[
             {"name":"gum", "type":"sweet", "price":"2"},
             {"name":"chocolate", "type":"tasty", "price":"3"}
        ]
    }
]

但是当我尝试在mongoose中做同样的事情时,candyTypes数组会变回空白:

Users.findOne({ 'username': username, 'tasks.id':taskId }, {'tasks.$':1}, function (err, data) {
        console.log(data);
}); 

/* returns */

"tasks":[
    {           
        "id":0,
        "title":"Candy",
        "description":"Lots of candy for you",
        "category":"food",
        "cost":2500,
        "candyTypes":[]
    }
]

我是MongoDB和Mongoose的新手,但在搜索和查看文档之后,我无法弄清楚我缺少的是什么。

更新

我有几个用户请求它,所以这是我的mongoose架构:

var UserSchema = new mongoose.Schema({
    username:String,
    name:String,
    tasks:[{
        id: Number,
        title: String,
        description:String,
        category: String,
        cost: Number,
        candyTypes:[{
            title:String, 
            type:String, 
            value:String
        }]
    }]
});

2 个答案:

答案 0 :(得分:0)

使用Mongoose,你必须填充candyTypes数组:

import numpy as np

text="""19, 11, 43
19, 12, 23
19, 13, 2
19, 14, 90
20, 11, 12
20, 12, 0
20, 13, 98
20, 14, 2
21, 11, 43
21, 12, 8
21, 13, 55
21, 14, 34"""

A_import=np.matrix(text.replace('\n',';')) 
A=A_import[:,2].reshape(3,4)
A

请参阅文档:http://mongoosejs.com/docs/populate.html

答案 1 :(得分:0)

我认为这与你声明一个名为type的字段有关,该字段在Mongoose中也有特殊含义,即表示字段的类型。

如果您将该字段重命名为其他字段(candyType),它可能会更好。

或者,您可以使用typeKey选项让Mongoose使用不同的属性名称来表示字段类型。

另外,您的文档包含字段price,但您的架构将其命名为value