[
{
"_id": "58b89de6a480ce48c8f3742d",
"name": "Core Site",
"version": "1.0.0",
"author": "Jane Doe",
"vendor": "Online Banking",
"steps": [
{
"name": "Step 1: Fun Stuff",
"dependencies": "1,2,3,4",
"resource": "TS",
"weight": 0
},
{
"name": "Step 2: Weird Stuff",
"dependencies": "3,4",
"resource": "PS",
"weight": 1
}
]
},
{
"_id": "58b8a22097fbe41746827ac7",
"name": "Online Statements",
"version": "1.0.0",
"author": "John Doe",
"vendor": "Online Banking",
"steps": [
{
"name": "Step 1: Fun Stuff",
"dependencies": "1,2,3,4",
"resource": "TS",
"weight": 0
}
]
}]
我已将此信息保存到MongoDB中,但当我尝试获取此信息时,子文档“Steps”不包含我使用Robomongo可以看到的_id。
我的架构如下:
// grab the things we need
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var stepSchema = new Schema({
name: { type: String, required: true},
dependencies: String,
resource: String,
weight: Number
})
// create a schema
var sopSchema = new Schema({
name: { type: String, required: true, unique: true },
version: String,
author: String,
vendor: String,
steps: [stepSchema]
});
// the schema is useless so far
// we need to create a model using it
var Sop = mongoose.model('Sop', sopSchema);
// make this available to our users in our Node applications
module.exports = Sop;
我的最终目标是检查步骤是否已包含在内,并在前端进行更改时进行更新。所以我想得到这个参考,以确保我有正确的子文档。
我的get语句在我的nodejs服务器中如下。
router.route('/sops')
.get(function(req, res) {
Sop.find(function(err, sops) {
if (err)
res.send(err);
var subdoc = sops[0].steps[0];
console.log(subdoc);
res.json(sops);
});
})
答案 0 :(得分:0)
MongoDB不会为您的子文档添加_id。您需要手动添加它。
所以:
"steps": [
{
"_id": new ObjectId(),
"name": "Step 1: Fun Stuff",
"dependencies": "1,2,3,4",
"resource": "TS",
"weight": 0
}
]
答案 1 :(得分:0)
Link to Article that Fixed the issue
var stepSchema = new Schema({
name: { type: String, required: true},
dependencies: String,
resource: String,
weight: Number
},{ _id: true });
在末尾添加了_id:true属性以强制生成_id。