test.js文件包含.create
函数,该函数在运行时显示类型错误。我已经尝试过插入功能保存功能,但它根本不将它识别为功能。我无法找到create function中的类型错误。
test.js文件
const mongoose = require('mongoose')
const Post = ('/database/models/Post')
mongoose.connect('mongodb://localhost/nodejs-test-blog')
// Post.find({}, (error, posts) => {
// console.log(error, posts)
// })
Post.create({
title: 'My second blog post',
description: 'Second Blog post description',
content: 'Second Lorem ipsum content.'
}, (error, post) => {
console.log(error, post)
})
Post.js文件
const mongoose = require('mongoose')
///
const PostSchema = new mongoose.Schema({
title: String,
description: String,
content: String
})
const Post = mongoose.model('Post', PostSchema)
module.exports = Post
使用mongodb的定义架构路径
require('./database/models/Post')
我会这样做的
require('./database/models/Post');
const mongoose = require('mongoose');
const Post = mongoose.model('Post);
如果你有很多模型,你可能想要创建一个不同的文件并要求所有模型在一起并需要这个新文件
const glob = require('glob');
const path = require('path');
// grab all mongo models name to require them
glob.sync('./database/models/**/*.js').forEach(file => {
require(path.resolve(file));
});
然后在你的test.js文件中
require('./path/to/models.js');
const mongoose = require('mongoose');
const Post = mongoose.model('Post);
导入架构时必须表示对象。试试这个。
const Post = ('/database/models/Post').Post;