使用`clone`和`Object.assign`方法在mongoose中克隆/扩展模式有什么区别?

时间:2018-04-08 04:56:37

标签: node.js mongodb mongoose

我的目的是克隆/扩展具有不同集合的通用模式,有两种方法可以实现我的目的,我想知道这些方法之间的区别:

const extendSchema = (Schema, definition, options) =>
  new MongooseSchema(Object.assign({}, Schema.obj, definition), options);

const CommonSchema = new MongooseSchema({
  name: {
    type: String,
    unique: true,
  },
  logo: String,
  owner: {
    name: String,
    avatar: String,
    reference: {
      type: ObjectId,
      ref: 'User',
    },
  },
});

const AnthorSchema = extendSchema(CommonSchema, { periverImage: String });

第二个是:

const CommonSchema = new MongooseSchema({
  name: {
    type: String,
    unique: true,
  },
  logo: String,
  owner: {
    name: String,
    avatar: String,
    reference: {
      type: ObjectId,
      ref: 'User',
    },
  },
});

const AnthorSchema = CommonSchema.clone();
AnthorSchema.add({ previewImage: String });

1 个答案:

答案 0 :(得分:0)

架构上的clone方法不仅复制架构的obj属性,还会克隆静态,虚拟,实例方法等。

一个简短的例子:

#!/usr/bin/env node
'use strict'

const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost/test')
const Schema = mongoose.Schema

const original = new Schema({
  name: String
})

original.statics.findAThing = function (n) {
  return this.find({ name: n }).exec()
}

const dupe = Object.assign({}, original.obj, { age: Number })

const clone = original.clone()

const Dupe = mongoose.model('dupe', dupe)
const Clone = mongoose.model('clone', clone)

const boo = new Dupe({
  name: 'casper',
  age: 93
})

const jango = new Clone({
  name: 'fett'
})

async function run () {
  await Dupe.remove({})
  await Clone.remove({})
  await boo.save()
  await jango.save()
  let doc = await Clone.findAThing('fett')
  console.log(doc)
  let fail = await Dupe.findAThing('casper')
  console.log(fail)
  return mongoose.connection.close()
}

run().catch(console.error)

输出:

stack: ./49714558.js
[ { _id: 5ac9e0f3d1d7d65547d3fdd1, name: 'fett', __v: 0 } ]
TypeError: Dupe.findAThing is not a function
    at run (/Users/lineus/dev/Help/mongoose5/stack/49714558.js:39:25)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:188:7)
^C
stack:

您可以在node_modules/mongoose/lib/schema.jsmongoose.Schema source on github中查看schema.clone的来源。