无法使用 mongoosejs return 子文档的 _id

Unable to return _id of a subdocument using mongoosejs

[
{
    "_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);
    });
})

MongoDB 不会为您的子文档添加 _id。您需要手动添加。

所以:

"steps": [
        {
            "_id": new ObjectId(),
            "name": "Step 1: Fun Stuff",
            "dependencies": "1,2,3,4",
            "resource": "TS",
            "weight": 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。