我想在用戶創建一個新文檔後將文檔_id保存到另一個模式的數組中。簡而言之:用戶保存視頻URL,並且我想將視頻的文檔_id保存到用戶架構中的數組中。我無法弄清楚如何做到這一點。這裏是我的模型文件:Mongoose在嵌入架構時分開文檔?
videos.js:
// Video Model
// -------------
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// Embedded document schema
var NotesSchema = new Schema({
timecode : String,
text : String
});
// Main schema
var VideoSchema = new Schema({
title : String,
url_id : String,
notes : [NotesSchema]
});
module.exports = mongoose.model('Note', NotesSchema);
module.exports = mongoose.model('Video', VideoSchema);
account.js:
// Account Model
// -------------
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Video = require('../models/videos.js');
var passportLocalMongoose = require('../node_modules/passport-local-mongoose/lib/passport-local-mongoose.js');
var AccountSchema = new Schema({
username: String,
salt: { type: String, required: true },
hash: { type: String, required: true },
videos: [VideoSchema] // <- need to save here
});
AccountSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model('Account', AccountSchema);
這是我現在怎麼有代碼的設置來創建文檔並保存到MongoDB的。
var video = new Video({
title : req.body.title,
url_id : req.body.url_id
});
video.save(function(err) {
if (err) {
console.log(err);
} else {
res.redirect('videos/' + video._id);
console.log('video saved.');
console.log('video information: ' + video);
}
});
基本上,我不知道如何保存視頻和只發送視頻文檔_id到帳戶架構的陣列。我該怎麼做呢?
編輯:
儘管執行建議的修復,data._id
不保存到帳戶架構內的陣列。沒有錯誤被拋出。當我使用mongo CLI檢查帳戶時,該數組爲空。
這裏是我的電流變化:
的Video.js
// Video Model
// -------------
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var NotesSchema = new Schema({
timecode : String,
text : String
});
var VideoSchema = new Schema({
title : String,
url_id : String,
notes : [NotesSchema]
});
module.exports = mongoose.model('Note', NotesSchema);
module.exports = mongoose.model('Video', VideoSchema);
account.js
// Account Model
// -------------
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Video = require('../models/videos');
var passportLocalMongoose = require('../node_modules/passport-local-mongoose/lib/passport-local-mongoose.js');
var AccountSchema = new Schema({
nickname: String,
birthday: Date,
videos: [{ type: Schema.Types.ObjectId, ref: 'Video' }]
});
AccountSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model('Account', AccountSchema);
視頻route.js
var util = require('util');
var mongoose = require('mongoose');
var Video = require('../models/videos');
var Account = require('../models/account');
var video = new Video({
title : req.body.title,
url_id : goodVimeoId
});
video.save(function(err, data) {
if (err) {
console.log(err);
} else {
Account.findOne({username : req.user.username}, function(err, result) {
result.videos.push(video._id);
res.redirect('videos/' + video._id);
});
}
});
爲什麼任何建議視頻數據未保存到賬戶?再次感謝。
如果你只是存儲'了'_id' AccountSchema.videos「,那麼該字段可能應該定義爲一個ObjectId參考數組而不是嵌入式對象數組。 – JohnnyHK 2013-03-12 12:43:49