将mongodb文档存储在另一个文档中

问题描述:

我试图将MongoDB文档从一个集合保存到另一个集合。我想通过我的API端点进行检索时,它看起来像这样。我单独创建错误,并希望通过ID通过机器加入。将mongodb文档存储在另一个文档中

{ 
    "_id": "59634780c464263b28a6891a", 
    "name": "GLUE-SM-21", 
    "status": false, 
    "__v": 0, 
    "error": { 
     "_id" : ObjectId("59769b9ad1050f244cadfced"), 
     "count" : 5, 
     "name" : "Error-001-J", 
     "__v" : 0 
    } 
} 

但我得到这个。

{ 
    "_id": "59634780c464263b28a6891a", 
    "name": "GLUE-SM-21", 
    "status": false, 
    "__v": 0, 
    "error": [ 
     "59769b9ad1050f244cadfced" 
    ] 
} 

这里我附上我目前的工作。

错误模式

var mongoose  = require('mongoose'); 
var Schema  = mongoose.Schema; 

var ErrorSchema = new Schema({ 
    name: String, 
    count: Number 
}); 

module.exports = mongoose.model('Error', ErrorSchema); 

机模式

var mongoose  = require('mongoose'); 
var Schema  = mongoose.Schema; 
const ObjectId = Schema.Types.ObjectId; 

var Error = require('./error'); 

var MachineSchema = new Schema({ 
    name: String, 
    status: Boolean, 
    error: [{ type: ObjectId, ref: 'Error', default: null }] 
}); 

module.exports = mongoose.model('Machine', MachineSchema); 

在默认情况下没有错误。这是我的保存代码。

 var machine = new Machine();  // create a new instance of the Machine model 
     machine.name = req.body.name; // set the machine name (comes from the request) 
     machine.status = 1; // set the machine status (comes from the request) 
     machine.error = null; 

     machine.save(function(err) { 
      if (err) 
       res.send(err); 

      res.json({ message: 'Machine created!' }); 
     }); 

这是我的更新代码。

Machine.findById(req.params.machine_id, function(err, machine) { 

      if (err) 
       res.send(err); 

      machine.name = machine.name; 

      if(req.body.error && machine.status) { 
       machine.status = false; 
      } else if(!req.body.error && !machine.status) { 
       machine.status = true; 
      } 
      machine.error = req.body.error; 
      machine.save(function(err) { 
       if (err) 
        res.send(err); 

       io.emit('machine', machine); 

       res.json({ message: 'Machine updated!' }); 
      }); 

     }); 
+0

问题是,'MachineSchema'“仍然”只需要存储ObjectId'的数组。因此,即使您尝试以不同的格式进行存储,“模式”也会出错或“投射”到已注册的类型。您需要使用** new **模式注册新模型,**或**在更多“原始”代码中进行转换,而不使用任何模式。那么当然你需要注册一个适合你的新数据结构的模式。 –

我找到了解决办法。

我已将错误文档的对象ID保存为我的机器文档中的错误属性。我已经使用更新我的代码在mongo上填充函数。

Machine.find().populate("error").exec(
      function(err, machines) { 
      if (err) 
       res.send(err); 

      res.json(machines); 
     } 
     );