2017-04-14 127 views
0

我試圖嵌入一個子文檔到我的主要文件,就像這樣:個人嵌套子文檔貓鼬

這是主要的document.js

var mongoose = require('../../db/mongodb.connector'), 
    Schema = mongoose.Schema; 

require('./document.model'); 
var Document= mongoose.model('Document'); 
require('./alert.model'); 
var Alert = mongoose.model('Alert'); 

    var userSchema = new Schema({ 
     name:  { type: String } 
     created:  { type: Date, default: Date.now()}, 
     alerts:  {type: Schema.ObjectId,ref: 'Alert'}, 
     documents: [{type: Schema.ObjectId,ref: 'Document'}], 

    }); 

module.exports = mongoose.model('User', userSchema); 

這是嵌入document.js

var mongoose = require('../../db/mongodb.connector'), 
    Schema = mongoose.Schema; 


var alertsSchema = new Schema({ 
    push:    {type: String, default: "true"}, 
    email:    {type: String, default: "false"}, 
    sms:    {type: String, default: "false"} 
}); 

module.exports = mongoose.model('Alert', alertsSchema); 

當我添加一個新用戶的文件是這樣的:

exports.insertUser = function (userData, res) { 

     var user = new User({ 
      name: userData.name, 
      alerts: {push: "true", email:"false", sms: "false"} 

     }); 

     user.save... 

... 

返回的數據是這樣的:

{ name: 'name', 
    documents: [], 
    created: 2017-04-14T10:22:05.612Z 
} 

的問題是,我不知道如果我做正確的嵌入文檔的sintax由於插入不返回任何錯誤,但警報對象沒有按」 t出現在插入的新文檔中。

會出現什麼問題?

回答

2

你做錯了。您需要先保存警報文檔,然後在用戶文檔中使用其ID。

let alertDoc = await new Alert({push: "true", email:"false", sms: "false"}).save(); 

// now use the id in the user doc 
await new User({name: userData.name,alerts: alertDoc._id }).save() 

如果你想嵌入整個文件,而不是隻存儲ref。您可以修改用戶模型的模式。像這樣定義你的模式。

var alertsSchema = new Schema({ 
    push:    {type: String, default: "true"}, 
    email:    {type: String, default: "false"}, 
    sms:    {type: String, default: "false"} 
}); 
.... 

var userSchema = new Schema({ 
    name:  { type: String } 
    created:  { type: Date, default: Date.now()}, 
    alerts:  alertsSchema, 
    documents: [{type: Schema.ObjectId,ref: 'Document'}], 
}); 
.... 

// now this should work 
var user = new User({ 
    name: "<some name>", 
    alerts: {push: "true", email:"false", sms: "false"} 
}); 
+0

但我想將完整的對象嵌入到主文檔中,而不是它們的參考。在主模型中使用ref的原因是爲了清除代碼。將單獨文檔的模式導入主文檔的正確方法是什麼? – Hanzo

+0

我已經更新了答案。 – Anand

+0

有什麼辦法維護其他文件中的警報模式,然後導入到userschema文件中? – Hanzo

0

userSchema有一個小問題。從您的架構定義中,它看起來像只存儲對alertsdocuments的引用。這裏的正確語法是alerts: {type: Schema.Types.ObjectId,ref: 'Alert'}。請注意額外類型在裏面。

此處的另一個問題是,您正嘗試在user文件中存儲完整的alert對象。貓鼬不允許這樣做,正如在你的模式中,你告訴貓鼬只保存對alert文檔的引用。所以你需要在這裏做的是,創建一個alert文件,得到它的_id然後將其存儲在alert字段的user文件中。

無論何時您想要獲取完整的用戶架構,只需要populatealertdocuments

希望這個答案可以提高你對貓鼬模式工作原理的理解。