在另一个模式中导入自定义猫鼬模式

时间:2019-01-08 01:42:00

标签: node.js mongodb mongoose mongoose-schema

我的软件具有猫鼬模式,我们称其为carSchema,并且正在导出名为carSchema的{​​{1}}模型。示例:

Car

现在说我的软件在另一个文件中有另一个名为/* Car.js */ var carSchema= new Schema({ _id: Schema.Types.ObjectId, type: String, wheels: Number }); carSchema.statics.drive = async function(){ ... } module.exports = mongoose.model('Car', carSchema); 的架构,其中使用了carSchema:

lotSchema

如何正确导入或导出/* Lot.js */ var lotSchema = new Schema({ _id: Schema.Types.ObjectId, carArr: [carSchema] }); lotSchema.statics.getAllId = async function(){ return carSchema[0]['_id'] } 以便在carSchema中使用?一个简单的lotSchema就足够了吗?

3 个答案:

答案 0 :(得分:2)

如果您不使用不使用es6 / 7,则可以这样做

 /* Car.js */
    const carSchema= new Schema({
        _id: Schema.Types.ObjectId,
        type: String,
        wheels: Number
    });

    carSchema.statics.drive = async function(){
        ...
    }
    module.exports.carSchema = carSchema;

    module.exports.carModel = mongoose.model('Car', carSchema);





 /* Lot.js */
    const { carSchema , carModel } = require('./Car.js');
    var lotSchema = new Schema({
        _id: Schema.Types.ObjectId,
        carArr: [carSchema]
    });

    lotSchema.statics.getAllId = async function(){
        return carSchema[0]['_id']
    }

答案 1 :(得分:0)

您可以使用Populate

  

填充是自动替换指定内容的过程   文档中包含其他集合中文档的路径。我们   可以填充单个文档,多个文档,普通对象,   多个普通对象,或查询返回的所有对象。

示例:

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

const carSchema= new Schema({
    _id: Schema.Types.ObjectId,
    type: String,
    wheels: Number
});

const lotSchema = new Schema({
    _id: Schema.Types.ObjectId,
    cars: [{ type: Schema.Types.ObjectId, ref: 'Car' }]
});

mongoose.model('Car', carSchema);
mongoose.model('Lot', lotSchema);

现在,要填充作品,您首先需要创建汽车对象car = new Car({})和很多对象lot = new Lot({}),然后:

lot.cars.push(car);
lot.save(callback); 

答案 2 :(得分:0)

您可以在Car.js中完成

module.exports = {
  useCarSchema: function(myCollection) {
    return mongoose.model('Car', carSchema, myCollection);
  }
}

这在Lot.js中

var carSchema     = require('./Car.js');
var Car =  carSchema.useCarSchema(myCollection);
相关问题