如何在ExpressJs中引用其他模型值?

时间:2017-03-16 19:36:17

标签: node.js angular express

我有一个在MEAN堆栈中使用的员工信息模型,并希望在商店模型中引用他们将要工作的商店名称,以下是正确的吗?

雇员:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var muv = require('mongoose-unique-validator');

var schema = new Schema({
    firstName: {type: String, required: true},
    lastName: {type: String, required: true},
    empId: {type: String, required: true, unique: true},
    num: {type: String, required: true},
    job: {type: String, required: true},
    store: {type: Schema.Types.storeName, ref: 'Stores'},
});

schema.plugin(muv);

module.exports = mongoose.model('Message', schema);

商户:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var schema = new Schema({
    storeName: {type: String, required: true},
    lat: {type: String, required: true},
    long: {type: String, required: true},
});

module.exports = mongoose.model('Stores', schema);

1 个答案:

答案 0 :(得分:0)

你关闭了!您想要引用商店的ID,而不是名称。当Mongoose执行“加入”时,它会在store个人资料字段中看到ObjectID商店,并将其与Stores集合中的ObjectID相匹配。

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var muv = require('mongoose-unique-validator');

var schema = new Schema({
    firstName: {type: String, required: true},
    lastName: {type: String, required: true},
    empId: {type: String, required: true, unique: true},
    num: {type: String, required: true},
    job: {type: String, required: true},
    store: {type: type: Schema.ObjectId, ref: 'Stores'},  //Reference store ObjectId.
});

schema.plugin(muv);

module.exports = mongoose.model('Message', schema);