活动用户和计算机之间的交互 ​​- MongoDB / Nodejs

时间:2017-12-20 12:41:27

标签: node.js mongodb mongoose

我正在为网吧建立一个网站,我需要指明“那个特定用户”正在使用“那个特定的计算机”。 这是我到目前为止所做的:

    var computerSchema = mongoose.Schema({  
    name: String, 
    type: String, 
    gpu: String,
    cpu: String, 
    memory: String,
    cm: String,
    usedBy : {type: String, default: null},
    active: {type: Boolean, default:false, ref:'user'}

});



 var userSchema = mongoose.Schema({ 

    firstname: String,
    lastname: String,
    age: Number,
    address: String,
    mail: String,
    password: String,
    status: String,
    here: {type: Boolean, default:false},
    created_date: Date,
    updated_date: Date,
    active_hash: String,
    role_id: { type: Number, default: 2 }
});

userSchema.virtual('users', {
    ref: 'computer',
    localField:'_id',
    foreignField:'active'
})

1 个答案:

答案 0 :(得分:1)

请执行此操作,我认为您可以删除userSchema.virtual,并更新您的userSchema,以便为每个用户提供如下计算机参考:

var userSchema = mongoose.Schema({
    firstname: String,
    lastname: String,
    age: Number,
    address: String,
    mail: String,
    password: String,
    status: String,
    here: {type: Boolean, default:false},
    created_date: Date,
    updated_date: Date,
    active_hash: String,
    role_id: { type: Number, default: 2 },
    computerId: {ref: 'computer'} // Your new reference to a computer _id
});

然后,如果你想用他的电脑找到一个用户,你可以像这样使用mongoose populate

UsersModel.find().populate('computerId').exec(function(err, users) {
    if (err) throw err;
    console.log(users); // display users with affected computers if exists
});

希望它有所帮助。