【发布时间】:2015-01-29 22:04:57
【问题描述】:
我正在尝试使用 mongoose (_id) 分配的 ID 链接我的 2 个 mongoose 模式 我有一个用户架构和一个服务器架构,每台服务器都应该有 1 个用户作为所有者,但每个用户都可以拥有许多服务器。所以我将req.user.id(来自passportJS)保存在服务器模式中,并且用户模式中有一个数组,我想在创建服务器时推送服务器的ID。我还没有完全使用填充,因为我不明白如何从即将创建的服务器中获取 ID 并将其推送到用户服务器数组
这是我的服务器架构:
var mongoose = require ('mongoose');
var timestamps = require('mongoose-times');
var Schema = mongoose.Schema;
var ServerSchema = new Schema({
name: String,
imgurl: String,
address: String,
port: String,
tags: Array,
votifier :{
enabled: Boolean,
address: String,
port: String,
pubKey: String
},
ownerID: {type: Schema.ObjectId, ref: 'User'},
upvotes: {type: Number, default: 0}
});
ServerSchema.plugin(timestamps);
module.exports = mongoose.model('Server', ServerSchema);
这是我的用户架构:
var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
var timestamps = require('mongoose-times');
var Schema = mongoose.Schema;
var userSchema = Schema({
local :{
username: {type: String, required: true},
password: {type: String, required: true}
},
email: {type: String, required: true},
imgId: String,
servers: [{type: Schema.ObjectId, ref: 'Server'}]
});
userSchema.plugin(timestamps);
//methods
//gen hash
userSchema.methods.generateHash = function(password, next){
bcrypt.hash(password, bcrypt.genSaltSync(8), null, next);
console.log(password + ': Password has generated hash');
};
userSchema.methods.validPassword = function(candidatePassword, cb) {
bcrypt.compare(candidatePassword, this.local.password, function(err, isMatch){
if(err) return cb(err);
cb(null, isMatch);
});
};
module.exports = mongoose.model('User', userSchema);
如何获取正在创建的服务器的 _ID 并将其推送到用户架构中的数组,我将使用服务器架构中的 OwnerID 找到ByID?
任何帮助将不胜感激,如果这是完全错误的方法,请告诉我!谢谢
【问题讨论】: