我的目的是克隆/扩展具有不同集合的通用模式,有两种方法可以实现我的目的,我想知道这些方法之间的区别:
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 });
最佳答案
模式上的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.js
或 mongoose.Schema source on github 中查看 schema.clone 的源代码.
关于node.js - 使用 `clone` 和 `Object.assign` 方法在 Mongoose 中克隆/扩展模式有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49714558/