node.js - 引用Mongoose多个文档

标签 node.js mongodb mongoose reference

我正在尝试使用 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 但没有成功

最佳答案

在您的 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"
      }
    ]
  }
]

关于node.js - 引用Mongoose多个文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42309870/

相关文章:

node.js - ObjectId并在mongodb中查找

node.js - 从 node.js 作为一个完整的服务器端新手开始?

mongodb - bottle-cork 登录后如何加载MongoDB数据库内容 'in place'?

node.js - 使用 Mongoose 中继承的文档进行填充

mongodb - 如果我不指定要更新的字段, Mongoose findOneAndUpdate 将无法正常工作

node.js - 为什么不在 package.json 文件中指定特定的包版本?那么我们就不需要package-lock.json

javascript - 如何使用 Passport.js 本地策略检查当前密码并(如果正确)更新密码

python - 在 Mongodb 中存储 Numpy 或 Pandas 数据

mongodb - Golang mongo驱动性能

javascript - (Mongo/Mongoose) 如何处理等待多个查询结果