在用户创建新文档后,我想将文档 _id 保存到另一个模式的数组中。简而言之:用户保存了一个视频 URL,我想将视频的文档 _id 保存到用户架构中的一个数组中。我无法弄清楚如何做到这一点。这是我的模型文件:
视频.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);
帐户.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
但并未保存到 Account 架构内的数组中。没有错误被抛出。当我使用 mongo CLI 检查帐户时,数组为空。
以下是我目前的更改:
视频.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);
视频路由.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);
});
}
});
关于为什么视频数据没有保存到帐户的任何建议?再次感谢。