【发布时间】:2017-08-18 01:20:28
【问题描述】:
我有一个简单的嵌入文档:
{
"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"}
]
}
]
但是当我尝试在猫鼬中做同样的事情时,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 还很陌生,但是在搜索和查看文档之后,我无法弄清楚我缺少什么。
更新
我有几个用户请求它,所以这是我的猫鼬模式:
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
}]
}]
});
【问题讨论】:
-
你能告诉我们你的架构定义吗?
-
试着控制你的用户名和任务 ID 是否与你用于 mongo shell 的相同
-
是的,它们是一样的。实际上我在这个数据库中只有一个测试用户
-
您可以尝试在
UserSchema之前定义CandyTypeSchema吗? 1. 定义var CandyTypeSchema = new Schema({ name: String, type: String, value:String });和 2. 在tasks属性中引用candyTypes:[CandyTypeSchema]。我猜它是 mongoose 不支持/不喜欢的深度嵌入级别。 -
我试图避免使用引用,主要是因为这是非常少量的数据,添加引用和不同的模式会不必要地增加整个应用程序的复杂性。 Mongoose 不支持嵌入数据吗?我浏览了他们的文档,但找不到任何关于使用嵌入式数据的限制。如果是这样的话,我可能只需要放弃 mongoose 并使用 MongoClient 驱动程序