【问题标题】:Link mongoose schemas using ID's pushed to an array?使用推送到数组的 ID 链接猫鼬模式?
【发布时间】: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?

任何帮助将不胜感激,如果这是完全错误的方法,请告诉我!谢谢

【问题讨论】:

    标签: express mongoose


    【解决方案1】:

    你可以像这样创建一个新的服务器:

    newServer = new ServerSchema(...);
    

    然后保存:

    newServer.save(callback);
    

    回调应该被定义为对实际保存的结果做任何你想做的事情。假设您有一个函数 updateUser 接收 userId 和 serverId 并将 serverId 推送给该 Id 的用户。 那么你的回调应该是......

    callback = function(serverSaveErr, serverSavedDoc) {
      if (serverSaveErr) { handle errors ... }
      else { updateUser(userId, serverSavedDoc._id }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-10-13
      • 2021-02-09
      • 1970-01-01
      • 2016-01-29
      • 2019-03-22
      • 2015-02-12
      • 1970-01-01
      • 2017-01-11
      • 2018-09-19
      相关资源
      最近更新 更多