【问题标题】:Referance multiple documents Mongoose参考多个文档 Mongoose
【发布时间】:2017-02-18 09:45:26
【问题描述】:

我正在尝试使用 mongoose 连接 3 个不同的文档(主要是为了学习如何使用它),我设置了 3 个不同的架构,如下所示:

(它们都在自己的文件中)

const Books = new Schema({
  title: { type: String, required: true, unique: true },
  description: String,
  author: { type: mongoose.Schema.Types.ObjectId, ref: 'Authors' },
  stores: [{
    available: Number,
    store: { type: mongoose.Schema.Types.ObjectId, ref: 'Stores' }
  }]
});

exports.Books = mongoose.model('Books', Books);

const Authors = new Schema({
  name: { type: String, required: true },
  description: String,
  born: Date,
  died: { type: Date, default: null }
});

exports.Authors = mongoose.model('Authors', Authors);

const Stores = new Schema({
  name: { type: String, required: true, unique: true },
  description: String,
  address: String
});

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

然后我添加以下数据:

author.name = 'Jonathan Swift';
author.description = 'old satiric bloke';
author.born = new Date(1667, 10, 30);
author.died = new Date(1745, 9, 19);
author.save()
  .catch((err) => console.log(err))
  .then(() => console.log('author saved'));

store.name = 'Book shop 1';
store.description = 'This is where the cool kids buy all there books!';
store.address = 'La La Land, 123 Combaja street';
store.save()
  .catch((err) => console.log(err))
  .then(() => console.log('store saved'));

book.title = 'gullivers travels';
book.author = '58a79345711f2350999e0911'; // _id from the author save
book.description = 'A book about a big guy in a small world';
book.stores = [{
  available: 8,
  store: '58a79345711f2350999e0912' // _id from the store save
}];
book.save()
  .catch((err) => console.log(err))
  .then(() => console.log('store saved'));

我发现的问题是,当我运行book.find() 时,它会返回:

[
  {
    "_id": "58a795b8298b50527412815c",
    "description": "A book about a big guy in a small world",
    "author": {
      "_id" : "58a79345711f2350999e0911",
      "born" : -9532947600000,
      "died" : -7075130400000,
      "description" : "old satiric bloke",
      "name" : "Jonathan Swift",
      "__v" : 0
    },
    "title": "gullivers travels",
    "__v": 0,
    "stores": [
      {
        "available": 8,
        "store": "58a79345711f2350999e0912",
        "_id": "58a795b8298b50527412815d"
      }
    ]
  }
]

我所期待/希望的是以与作者相同的方式获得整个商店,我是否遗漏了什么或者我应该如何去做才能达到预期的结果? 我试过populate,但没有成功

【问题讨论】:

    标签: node.js mongodb mongoose reference


    【解决方案1】:

    在您的 Books 模型中,authorstores.store 是参考,如果您不使用 populate(),则不应填充 author 字段。

    如果您直接指定您刚刚创建的商店和作者的_id

    var author = new Authors({
        name: 'Jonathan Swift',
        description: 'old satiric bloke',
        born: new Date(1667, 10, 30),
        died: new Date(1745, 9, 19)
    });
    
    author.save();
    
    var store = new Stores({
        name: 'Book shop 1',
        description: 'This is where the cool kids buy all there books!',
        address: 'La La Land, 123 Combaja street'
    });
    
    store.save();
    
    var book = new Books({
        title: 'gullivers travels',
        author: author._id, // _id from the author save
        description: 'A book about a big guy in a small world',
        stores: [{
            available: 8,
            store: store._id // _id from the store save
        }]
    })
    
    book.save();
    

    Books.find() 给出了预期的结果:

    [
      {
        "_id": "58a7a2529a8b894656a42e00",
        "title": "gullivers travels",
        "author": "58a7a2529a8b894656a42dfe",
        "description": "A book about a big guy in a small world",
        "__v": 0,
        "stores": [
          {
            "available": 8,
            "store": "58a7a2529a8b894656a42dff",
            "_id": "58a7a2529a8b894656a42e01"
          }
        ]
      }
    ]
    

    如果您想填充 stores.storeauthor,请使用:

    Books.find().populate([{path:'author'},{path:'stores.store'}]).exec(function(err, res) {
        console.log(JSON.stringify(res, null, 2));
    });
    

    正如预期的那样,authorstores.store 都已填充:

    [
      {
        "_id": "58a7a2529a8b894656a42e00",
        "title": "gullivers travels",
        "author": {
          "_id": "58a7a2529a8b894656a42dfe",
          "name": "Jonathan Swift",
          "description": "old satiric bloke",
          "born": "1667-11-29T23:00:00.000Z",
          "__v": 0,
          "died": "1745-10-18T22:00:00.000Z"
        },
        "description": "A book about a big guy in a small world",
        "__v": 0,
        "stores": [
          {
            "available": 8,
            "store": {
              "_id": "58a7a2529a8b894656a42dff",
              "name": "Book shop 1",
              "description": "This is where the cool kids buy all there books!",
              "address": "La La Land, 123 Combaja street",
              "__v": 0
            },
            "_id": "58a7a2529a8b894656a42e01"
          }
        ]
      }
    ]
    

    【讨论】:

    • 哇,这就是我犯错的地方,非常感谢伙计!顺便说一句,你知道作者是谁吗? (如果这有助于缩小范围,请使用邮递员)
    猜你喜欢
    • 2014-05-13
    • 1970-01-01
    • 1970-01-01
    • 2013-05-18
    • 1970-01-01
    • 2020-04-20
    • 2013-03-02
    • 2015-02-19
    • 2018-12-13
    相关资源
    最近更新 更多