问题描述
刚接触 MongoDB 并了解一些基本的 Node.js 应用程序。遵循 Node、Express 和 MongoDB 的在线教程。我有一些代码连接到远程集群并将文档推送到集合中。连接有效,但插入的文档是空的,因为它只包含自动生成的 ID。代码如下:
const DB = process.env.DATABASE.replace(
'<PASSWORD>',process.env.DATABASE_PASSWORD
);
mongoose
.connect(DB,{
useNewUrlParser: true,useCreateIndex: true,useFindAndModify: false,})
.then(() => console.log('DB Connection successful'));
const tourSchema = new mongoose.Schema();
({
name: {
type: String,required: [true,'A tour must have a name'],unique: true,},rating: {
type: Number,default: 4.5,price: {
type: Number,'A tour must have a price'],});
const Tour = mongoose.model('Tour',tourSchema);
const testTour = new Tour({
name: 'aaaa',rating: 3.0,price: 397,});
testTour
.save()
.then((doc) => {
console.log(doc);
})
.catch((err) => console.log('ERROR:',err));
输出如下:
如果我查看 Compass,我可以看到创建的空文档,因此连接有效。实际连接字符串是否有一些不同的查询字符串参数?以下是 MongoDB 连接字符串的当前查询字符串参数(这些是默认值):retryWrites=true&w=majority
知道我在代码中可能遗漏了什么吗?
谢谢!
解决方法
试试改变这个:
const tourSchema = new mongoose.Schema();
({
到:
const tourSchema = new mongoose.Schema({
,
在第 13 行,您没有正确定义架构并且其中没有定义实体,因为您在定义之前使用 ;
关闭了架构。
const DB = process.env.DATABASE.replace(
'<PASSWORD>',process.env.DATABASE_PASSWORD
);
mongoose
.connect(DB,{
useNewUrlParser: true,useCreateIndex: true,useFindAndModify: false,})
.then(() => console.log('DB Connection successful'));
const tourSchema = new mongoose.Schema()
({
name: {
type: String,required: [true,'A tour must have a name'],unique: true,},rating: {
type: Number,default: 4.5,price: {
type: Number,'A tour must have a price'],});
const Tour = mongoose.model('Tour',tourSchema);
const testTour = new Tour({
name: 'aaaa',rating: 3.0,price: 397,});
testTour.save()
.then((doc) => {
console.log(doc);
})
.catch((err) => console.log('ERROR:',err));