Я хотел бы сохранить документ _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);
});
}
});
Любые предложения о том, почему видеоданные не сохраняются на счет? Еще раз спасибо.
Если вы просто хранить '' _id' в AccountSchema.videos', то это поле должно, вероятно, быть определено как массив ObjectId ref, а не встроенный массив объектов. – JohnnyHK