Mongoose创build模型时出错(使用步骤)
当试图在Mongoose中创build模型时,出现以下错误
[TypeError:无法读取未定义的属性'选项]
我不知道是什么原因造成的
"use strict"; var Step = require('step'); var mongoose = require('mongoose'); var Schema = mongoose.Schema; function randomFunction() { var categorySchema = new Schema({ id: Number, name: String, description: String }, { collection: 'categories' }); var Category; //... mongoose.connect('mongodb://localhost/grouping'); new Step( function() { //Connect to mongodb var db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); db.on('open', this); }, function() { //Create model console.log(categorySchema); //Logs the schema object right Category = mongoose.Model('Category', categorySchema); }, function(err) { console.log(err); //Error here }); //... }
我对Mongo非常陌生(对节点来说相当新颖),但我完全不知道错误信息是什么意思。
我知道我有在架构中定义的选项,但我不知道它是如何定义的,任何人都可以指向正确的方向吗?
注意 – 这是一个很大的原始代码,这是一般的结构(实际上有一些代码在mongoose.Model('Cat...
下面mongoose.Model('Cat...
但它被跳过了,我假设是因为mongoose.Model
抛出的错误调用甚至不是一个console.log("Hello");
是直接打印它。
编辑我发现,在mongoose( this.schema
/ lib / document.js)试图得到this.schema
但它是未定义的
function Document (obj, fields, skipId) { //Line 37 this.$__ = new InternalCache; this.isNew = true; this.errors = undefined; var schema = this.schema; //-> undefined // ...
所以事实certificate,我不是残酷的,
mongoose.Model
应该是mongoose.model
您也可以获得调用此相同的错误。
MyModel = new mongoose.model('<your model name>', mySchema)
如果你确实删除了新的。
在Promise链中使用模型方法时,也会显示此错误消息,例如:
const Product = mongoose.model('Product', ProductSchema) ScrapProducts() .then(mapToModel) .then(Product.create)
要解决它,你必须确保你的mongoose模型保留其原始上下文。
const Product = mongoose.model('Product', ProductSchema) ScrapProducts() .then(mapToModel) .then(function(data) { return Product.create(data) })
或更好:
const Product = mongoose.model('Product', ProductSchema) ScrapProducts() .then(mapToModel) .then(Product.create.bind(Product))