2013-03-12 2 views
1

Я хотел бы сохранить документ _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 в массив в схеме учетной записи. Как мне это сделать?

EDIT:

Несмотря на реализацию предлагаемых исправлений, data._id не сохраняет в массив внутри схемы счета. Ошибка не возникает. Когда я проверяю учетную запись, используя CLI mongo, массив пуст.

Вот мои текущие изменения:

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); 
    }); 

    } 
}); 

Любые предложения о том, почему видеоданные не сохраняются на счет? Еще раз спасибо.

+0

Если вы просто хранить '' _id' в AccountSchema.videos', то это поле должно, вероятно, быть определено как массив ObjectId ref, а не встроенный массив объектов. – JohnnyHK

ответ

0

Проблема решена:

мне нужно добавить result.save(); после result.videos.push(video._id);, как так:

Account.findOne({username : req.user.username}, function(err, result) { 
     result.videos.push(video._id); 
     result.save(); 
     res.redirect('videos/' + video._id); 
    }); 
+1

fyi, вы должны принять ваш ответ – generalhenry

+0

Спасибо @generalhenry –

1

Только что заметил комментарий о ObjectId. Были обновлены ответ в соответствии с требованиями:

var ObjectId = Schema.ObjectId; 

    var AccountSchema = new Schema({ 
     username: String, 
     salt: { type: String, required: true }, 
     hash: { type: String, required: true }, 
     videos: [{type: ObjectId, ref: 'Video'}] // <- need to save here 
    }); 
.... 
.... 

    video.save(function(err, data) { 
    Account.findOne({username:req.body.username}, function(err, result) { 
     result.videos.push(data._id); 
    }); 
    }); 
+0

Привет @almypal и @JohnnyHK - Когда я использую 'req.body.username', я получаю' TypeError: Не могу прочитать свойство 'videos' of null'. Однако, когда я использую 'req.user.username', объект видео сохраняет значение' VideoSchema', но он не сохраняется в массиве ref 'AccountSchema' (массив пуст), а затем правильно перенаправляется. Любые предложения о том, как получить видео ObjectId в массиве ref? –

Смежные вопросы