首页 > 解决方案 > Mongoose 没有在 save() 函数上创建集合

问题描述

我有以下架构。

const mongoose = require('mongoose');

const JobSchema = new mongoose.Schema({
  posterId: {
    type: String,
    required: true,
  },
  title: {
    type: String,
    required: true,
  },
  location: {
    type: String,
    required: true,
  },
}, { timestamp: true });

module.exports = mongoose.model('Job', JobSchema);

我使用下面的代码将新数据保存到这个集合中。

const Job = require('../../models/Job');

new Job({
    posterId,
    title,
    location,
})
.save()
.then(job => {
    console.log('JOB: ', job) // consoles the newly added job to collection.
    if (job) {
        response.json({
            message: 'Job is saved successfully.',
        });
    } else {
        response.json({
            message: 'Job can not be saved at this time. Please try again later.',
        });
    }
})
.catch(error => {
    response.json(error);
});

上面的代码成功地将新信息保存到作业集合中,但是当我使用 mongodb CLI 在 mongoDB 中检查时。我在那里看不到任何工作集合,因此它没有创建集合。我做错了什么,我该如何解决?

标签: javascriptnode.jsmongodbmongoose

解决方案


推荐阅读