2017-07-25 63 views
0

我試圖將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 **模式註冊新模型,**或**在更多「原始」代碼中進行轉換,而不使用任何模式。那麼當然你需要註冊一個適合你的新數據結構的模式。 –

回答

0

我找到了解決辦法。

我已將錯誤文檔的對象ID保存爲我的機器文檔中的錯誤屬性。我已經使用更新我的代碼在mongo上填充函數。

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

      res.json(machines); 
     } 
     ); 
相關問題