简体   繁体   English

当我尝试引用其他模式的对象时,为什么猫鼬引用对我不起作用?

[英]Why doesn't mongoose ref work for me when I'm trying to reference objects of another schema?

I'm trying to access the attributes of an address of a store, but I keep on getting 'undefined'. 我正在尝试访问商店地址的属性,但是我一直在获取“未定义”。 Turns out that address is only an id, even though I declared a 'ref' in the address's schema. 事实证明,即使我在地址的架构中声明了“ ref”,该地址也只是一个id。 What am I doing wrong here? 我在这里做错了什么?

Output from initStores 来自initStores的输出

{ name: 'Wegmans',
  address: 53b998d9fcf740e07a4d03f7,
  _id: 53b998d9fcf740e07a4d03f8,
  items: [] }
53b998d9fcf740e07a4d03f7
undefined

routers/index.js 路由器/index.js

router.post('/initStores', function(req, res) {
    var address = new Address({
        street:     '650 Hylan Dr',
        city:       'Rochester',
        state:      'NY',
        zipcode:    '14623',
        telephone:  '123-456-7890'
    });
    // address.save();

    var store = new Store({
        name:   'Wegmans',
        address: address
    });

    console.log( store );
    console.log( store.address );
    console.log( store.address.street );
    // store.save();
}

models/address.js models / address.js

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

var AddressSchema = new Schema({
    type:      { type: String, default: 'Store' }, // Store, apartment, house, headquarter
    street:    { type: String, require: true }, 
    city:      { type: String, require: true },
    state:     { type: String, require: true },
    zipcode:   { type: String, require: true },
    country:   { type: String, default: 'United States' },
    telephone: { type: String, default: '555-555-5555' }
});

mongoose.model('Address', AddressSchema);

models/store.js models / store.js

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

var StoreSchema = new Schema({
    name:       { type: String, require: true },
    address:    { type: ObjectId, ref: 'Address' },
    items:      [ { type: ObjectId, ref: 'Item' } ]
});

mongoose.model( 'Store', StoreSchema );

For a referenced schema this code works absolutely as designed. 对于引用的架构,此代码绝对按设计工作。 Fields in the "Address" schema are not part of the the "Store" schema at all. “地址”模式中的字段根本不属于“存储”模式。 What the referenced design does here is just stores the _id value of the related document, where the rest of that document will reside in it's own collection. 参考设计在这里所做的只是存储相关文档的_id值,该文档的其余部分将驻留在其自己的集合中。

So, in fact you are actually creating these separately and only ever after a .populate() operation do the different documents actually "appear" to be "joined", just as they would appear in a native way if the document was in fact "embedded". 因此,实际上您实际上是在分别创建这些文件,并且仅在.populate()操作之后才将不同的文件实际“显示”为“加入”,就像如果文档实际上是“以本机方式显示”一样,嵌入式”。

Store.findById(store._id).populate("address").exec(err,newstore) {

    console.log(newstore);
});

Or since you really have the "store" object already and making sure "saves" have completed: 或者,因为您确实已经有了“商店”对象并确保“保存”已完成:

async.series(
  [
    function(callback) {
      address.save(function(err,address) {
        callback();
      });
    },
    function(callback) {
      store.save(function(err,store) {
        Store.populate(store,{ path: "address"},function(err,store) {
          console.log(store);
          callback();
        });
      });
    }
  ]
);

The only ways in which this can and "should" appear as a whole object without the .populate() which needs the data to be saved, is either by embedding the address so it is part of the "Store", and not saved to a different model and collection: 可以并且“应该”作为一个整体对象出现而没有需要保存数据的.populate()的唯一方法是通过嵌入地址使其成为“存储”的一部分,而不是保存到不同的模型和集合:

var StoreSchema = new Schema({
    name:       { type: String, require: true },
    address:    { 
        "type":    { type: String, default: 'Store' }, // Store, apartment, house, headquarter
        street:    { type: String, require: true }, 
        city:      { type: String, require: true },
        state:     { type: String, require: true },
        zipcode:   { type: String, require: true },
        country:   { type: String, default: 'United States' },
        telephone: { type: String, default: '555-555-5555' }
    },
    items:      [ { type: ObjectId, ref: 'Item' } ]
});

Or if your purposes are just purely logging on creation then you can convert and manipulate with .toObject() : 或者,如果您的目的仅仅是记录创建,则可以使用.toObject()进行转换和操作:

var raw = store.toObject();
raw.address = address.toObject();

console.log( raw );

But otherwise with a referenced model, the intention is that the data is not part of the same object until a .populate() is called. 但是,否则,对于引用的模型,其目的是在调用.populate()之前,数据不属于同一对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当我尝试移动跨度时,appendChild不起作用 - appendChild doesn't work when I'm trying to move span 为什么当我用 Axios 设置数据时它不起作用 - Why when I'm setting Data with Axios it doesn't work 我正在尝试使用正则表达式,但它不起作用。 给我一个提示 - I'm trying to use a regular expression but it doesn't work. Give me a hint 我正在尝试在 React 中实现搜索过滤器,但它不起作用,你能帮帮我吗? - I'm trying to implement a Search Filter in React, but it doesn't work, could you help me out? Mongoose 在文档更新时不遵守参考架构定义 - Mongoose doesn't respect ref schema definition upon document update 为什么'toPromise()'对我来说不起作用 - Why the 'toPromise()' doesn't work for me when 在 ZCCADCDEDB567ABAE643E15DCF0974E503Z 中引用另一个 Schema - Reference another Schema in Mongoose 当我按回车键时,我试图阻止默认行为,但它不起作用 - I'm trying to prevent default behavior when I hit enter but it doesn't work Mongoose:增加我的文档版本号不起作用,我在尝试保存时遇到版本错误 - Mongoose: Incrementing my documents version number doesn't work, and I'm getting a Version Error when I try to save 为什么 mongoose 填充数组时不起作用? - Why mongoose populate doesn't work when populating an array?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM