【发布时间】:2016-02-10 18:05:20
【问题描述】:
我是 Mongo db/Mongoose 的新手,这个问题是关于 mongoose 和集合之间的关系,我知道有很多关于如何完成这项工作的教程,但仍然无法理解一个简单的方法来完成这项工作。我有两个模型:
这是主要模型:
'use strict';
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var CategorySchema = new Schema({
name : String,
info : String,
items : [{ type: Schema.Types.ObjectId, ref: 'Item' }]
});
var itemsSchema = Schema({
name : String,
description : String,
price : Number
});
var Item = mongoose.model('Item', itemsSchema);
module.exports = mongoose.model('Category', CategorySchema);
我需要在类别集合中填充项目数组并创建两个集合之间的关系。
当我从邮递员发帖时,我可以看到项目数组正在创建,但我无法填充数组。
如果我确实得到了类别,这就是响应:
[
{
"_id": "564120be4123198a1f93feb5",
"name": "Classic",
"info": "this is the info",
"__v": 0,
"items": []
},
{
"_id": "5641220b02968e901f678ff5",
"name": "Classic",
"info": "this is the info",
"__v": 0,
"items": []
}
]
这是放到 api/categories/ 的结果
{
"_id": "564120be4123198a1f93feb5",
"name": "test again",
"info": "this is the info",
"__v": 1,
"items": []
}
期望的输出:
{
"_id": "564120be4123198a1f93feb5",
"name": "test again",
"info": "this is the info",
"__v": 1,
"items": [
{
"_id": "some id"
"name": "name",
"description": "lorem ipsup"
},
{
"_id": "some id"
"name": "name",
"description": "lorem ipsup"
},
{
"_id": "some id"
"name": "name",
"description": "lorem ipsup"
},
]
}
【问题讨论】:
-
您使用什么逻辑将项目插入到类别中?
-
@KevinB 我需要能够在将来删除单个项目。
-
您使用什么逻辑将项目插入到类别中?如果它工作正常,您应该在该数组中看到一个 id。我没有看到任何 ID。
-
@KevinB 我无法在数组中获取任何 ID。我正在关注以下文档mongoosejs.com/docs/populate.html
-
“我无法在数组中获取任何 id” 这就是我要指出的。如果数组中没有任何内容可以填充,.populate 将不会填充任何内容!目前它是空的,所以 .populate 不会改变它。要使 .populate 工作,该数组需要包含属于该类别的项目 ID。
标签: javascript json node.js mongodb mongoose