我是node.js,mongodb和mongoose的新手。我对mongoose上的ref对象有点问题。
这是我的代码
admin.js
router.post('/accounts/show_account/team/add_member/:account_id/:team_id', function(req,res){
var account_id = req.params.account_id;
var team_id = req.params.team_id;
var full_name = req.body.full_name;
var position = req.body.position;
var dateStarted = req.body.dateStarted;
var errors = req.validationErrors();
if (errors) {
// res.render('register',{errors:errors});
console.log('errors');
} else{
var newMember = new Members({
full_name : full_name,
position : position,
dateStarted : dateStarted
});
newMember.save(function(err,member){
if (err) {
console.log(err);
} else {
console.log(member);
}
});
}
});
model.js - >模式
var mongoose = require('mongoose');
var bcrypt = require('bcryptjs');
var Schema = mongoose.Schema;
var MemberSchema = mongoose.Schema({
full_name : {
type: String
},
current_position : {
type: String
},
dateStarted : {
type: String
},
is_admin: {
type: Boolean,
default : false
}
});
var member = module.exports = mongoose.model('Members', MemberSchema);
module.exports.createMember = function(newMember, callback){
newMember.save(function(err){
if (err) throw err;
});
}
team.js - >团队架构
var mongoose = require('mongoose');
var bcrypt = require('bcryptjs');
var Schema = mongoose.Schema;
var TeamSchema = mongoose.Schema({
team_name: {
type: String
},
date_created: {
type: Date
},
members: [{
type: mongoose.Schema.Types.ObjectId,
ref : member
}]
});
var Team = module.exports = mongoose.model('Team', TeamSchema);
module.exports.createTeam = function(newTeam, callback){
newTeam.save(function(err){
if (err) throw err;
});
}
我正在尝试加入团队架构和成员架构,但我不知道如何去做。
答案 0 :(得分:1)
您应该将架构相关名称添加为字符串
var mongoose = require('mongoose');
var bcrypt = require('bcryptjs');
var Schema = mongoose.Schema;
var TeamSchema = mongoose.Schema({
team_name: {
type: String
},
date_created: {
type: Date
},
members: [{
type: mongoose.Schema.Types.ObjectId,
ref : "Members"
}]
});
var Team = module.exports = mongoose.model('Team', TeamSchema);
module.exports.createTeam = function(newTeam, callback){
newTeam.save(function(err){
if (err) throw err;
});
}
现在,当您进行服务时,可以使用[populate][1]
函数“加入”您的模式。
如果您需要在 TeamSchema 文档中插入新的成员,只需添加新成员的 _id
var newMebers = new Members({...});
newMembers.save()
.then(function(newMember){
return TeamSchema.findById(<TeamId>,
{$push:{members:newMember._id});
})
.catch(function(err){ console.error(err)});