猫鼬引用子文档的方式不同?

时间:2019-03-11 06:06:31

标签: mongodb mongoose mongoose-schema

此语法直接来自有关子类型的猫鼬文档。但是,我也看到了对子文档的替代引用。有什么区别?

https://mongoosejs.com/docs/subdocs.html

var childSchema = new Schema({ name: 'string' });

var parentSchema = new Schema({
  // Array of subdocuments
  children: [childSchema],
  // Single nested subdocuments. Caveat: single nested subdocs only work
  // in mongoose >= 4.2.0
  child: childSchema
});

对子文档的另一种引用方式

var childSchema = new Schema({ name: 'string' });

mongoose.model('children', childSchema);

var parentSchema = new Schema({
  children: {
    type: Schema.Types.ObjectId,
    ref: 'children'
  },
});

2 个答案:

答案 0 :(得分:1)

区别非常简单。您只为子级定义架构的前者不会为数据库中的子级创建单独的集合,而是将整个子级文档嵌入父级。

后一版本中,您将通过调用mongoose.model 为子模式定义一个模型,该模型将在数据库中创建一个单独的子项集合,然后在父文档中引用子文档,而无需仅通过添加子_id将整个子文档嵌入到父文档中。

答案 1 :(得分:0)

我已经完成 Ravi Shankar Bharti 案例2 ,并提供一些数据写入示例。让我们使用一个书作家场景:

const authorSchema = new Schema({ name: 'string' });
const authorModel = mongoose.model('authors', authorSchema);
    
const bookSchema = new Schema({
  title: String,
  author: {
    type: Schema.Types.ObjectId,
    ref: 'author'
  },
});

const bookModel = mongoose.model('books', bookSchema)

const authorData = { name: "John Doe" }

// Check if author does exists. Insert if not or find if yes
const options = {
  upsert: true,
  new: true,
  setDefaultsOnInsert: true
};
const anAuthor = await authorModel.findOneAndUpdate(authorData, authorData, options)

// Insert a new book with reference to `anAuthor`
const aBook = new bookModel({ title: "MyBook" })
aBook.set({ author: anAuthor })
await aBook.save()

在这种语法中,子文档将单独存储,并且其引用ID(_id)将存储在父文档中。

在这种情况下,示例文档将如下所示:

// authors documents
{ _id : "authorId1" , name : "John Doe"}
{ _id : "authorId2" , name : "Iron Man"}
{ _id : "authorId3" , name : "Thor Odinson"}

//books document
{ 
  _id : "parent_random_generated_id"
  title: "MyBook",
  author : "authorId1",
  ...
}

要阅读,您可以使用populate

let result = await bookModel.find()
result = await authorModel.populate(result, { path: 'author' })