Mongoose解决了没有架构的问题

时间:2015-02-07 00:39:24

标签: node.js mongodb mongoose

我有2个架构:客户和地址。由于其他原因,必须首先注册地址模式。 如何在地址模式中的静态内对customer表执行查询?

我在想我需要访问原始mongo驱动程序并使用它执行查询 - 我不需要任何特殊的Mongoose验证/中间件,因此这不是问题。

如何使用Customer模型中的本机驱动程序访问Address表?或者有一种纯粹的猫鼬方式吗?请注意,O不希望在Customer表中创建引用和使用填充的引用。

2 个答案:

答案 0 :(得分:0)

您只需要从customer.js模型访问Address模型。

//Customer.js

var Address = require('./models/Address');

CustomerSchema = new mongoose.Schema({
    addresses: [{type: mongoose.Schema.ObjectId, ref:'Address'}]
});

CustomerSchema.statics.getAddressById = function getAddressById (id, next) {
    Customer.findOne({_id: id}, function (err, customer) {
        if (err || !customer) {
            return next(err || new Error('Customer not found with id' + id));
        }

        Address.find({_id: {$in : customer.addresses}}, next);
    }); 
}

var Customer = db.model('Customer', CustomerSchema);
module.exports = Customer;

我假设您的客户架构有一个addresses密钥,该密钥是一组地址。如果不是这种情况,请随意将其更改为单个地址。

答案 1 :(得分:0)

确定。我通过更改拨打var Customer = mongoose.model('Customer')电话的位置来解决我的问题。将此放在我的地址模型的顶部与所有其他要求导致模式注册错误。但是将它放在静态方法中就可以了。

所以:

AddressSchema.statics.myMethod = function() {
  var Customer = mongoose.model('Customer');