我有以下猫鼬模型:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var addressDefinition = require('./addressPersistenceModel');
var UserEntityModel = new Schema({
firstname: String,
lastname: String,
address: addressDefinition
});
mongoose.model('User', UserEntityModel);
地址的定义是这样完成的:
module.exports = {
street: String,
...
};
我出于可重用性的原因这样做。
在我的业务逻辑中,我这样做:
UserBusinessLogic.prototype.create = function(inputModel, callback) {
var user = new UserPersistenceModel();
user.firstname = inputModel.firstname;
user.lastname = inputModel.lastname;
...
user.save(function(error) {
...
}
});
};
我不想将输入中的所有值都分配给业务逻辑中的模型,而是希望将输入模型传递给我的模型(在构造函数中),如下所示:
var user = new UserPersistenceModel(inputModel);
应该读取输入中的所有值并将其分配给"字段"我的模特。
为此我想到了方法和/或静力学。据我所知,我应该使用一种方法,因为我正在处理"实例级别" (我想保存一份文件),对吧?我的方法怎么样?我不确定如何访问那里的字段。
更新
这就是UserCreateInputModel
的样子:
var Address = require('../address');
var UserCreateInputModel = function(req) {
this.alias = req.param('alias');
this.email = req.param('email');
this.firstName = req.param('firstName');
this.lastName = req.param('lastName');
this.password = req.param('password');
this.address = new Address(req);
};
module.exports = UserCreateInputModel;
这就是地址的样子:
var Address = function(req, persistenceModel) {
if(req !== null && req !== undefined) {
this.city = req.param('city');
this.country = req.param('country');
this.state = req.param('state');
this.street = req.param('street');
this.zipCode = req.param('zipCode');
}
if(persistenceModel !== null && persistenceModel !== undefined) {
this.city = persistenceModel.city;
this.country = persistenceModel.country;
this.state = persistenceModel.state;
this.street = persistenceModel.street;
this.zipCode = persistenceModel.zipCode;
}
};
module.exports =地址;
答案 0 :(得分:1)
您已经拥有猫鼬User
模型。您在业务逻辑中需要做什么:
// assuming you're doing a 'module.exports = mongoose.model('User', UserEntityModel);' in your schema file
var UserPersistenceModel = require('./your_user_schema_file.js');
UserBusinessLogic.prototype.create = function(inputModel, callback) {
// if your inputModel passed to this function is a javascript object like:
// {
// firstName: "First",
// lastName: "Last",
// ...
// }
var user = new UserPersistenceModel(inputModel);
...
user.save(function(error) {
...
});
};
<强>已更新强>
您错误地引用了地址模型。
假设您的module.exports = mongoose.model('Address', AddressEntityModel);
模型末尾有Adress
行,这就是您必须在User
模型中引用它的方式:
var UserEntityModel = new Schema({
firstname: String,
lastname: String,
address: { type: Schema.Types.ObjectId, ref: 'Address' }
});
您甚至不需要地址模型文件。
Mongoose只存储引用对象的id
。因此,您可以更改的引用地址中唯一的属性是id
(例如清理引用或将其指向另一个地址)。