没有生成自动_id

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了没有生成自动_id相关的知识,希望对你有一定的参考价值。

所以我有这个代码用于向数据库添加新项目,如下所示:

let parking = new Parking({
  name: req.body.name,
  country: mongoose.Types.ObjectId(req.body.country),
  reservationsEmail: req.body.reservationsEmail,
  location: mongoose.Types.ObjectId(req.body.location),
  commissionPercentage: req.body.commission,
  isConcept: true,
});

parking.save()
.then(parking => {
  res.send(parking);
}).catch(err => {
  res.send(err);
});

这给了我一个错误,保存前需要_id

{ MongooseError: document must have an _id before saving
    at new MongooseError (/Users/robin/www_node/parkos/node_modules/mongoose/lib/error/mongooseError.js:14:11)
    at Timeout._onTimeout (/Users/robin/www_node/parkos/node_modules/mongoose/lib/model.js:259:18)
    at ontimeout (timers.js:466:11)
    at tryOnTimeout (timers.js:304:5)
    at Timer.listOnTimeout (timers.js:267:5)
  message: 'document must have an _id before saving',
  name: 'MongooseError' }

为什么_id不会像它应该的那样自动添加?

这是我使用的模型:

const mongoose  = require('mongoose');
const ObjectId  = mongoose.Schema.ObjectId;
const isEmail   = require('validator/lib/isEmail');
const slugify   = require('../../lib/utils.js').slugify;

let parkingSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
  },
  slug: {
    type: String,
    required: true,
    default() {
      return slugify(this.name);
    }
  },
  country: {
    type: ObjectId,
    ref: 'Country',
    required: true,
  },
  reservationsEmail: {
    type: String,
    required: true,
    validate: [
      isEmail,
      'Please enter a valid emailaddress'
    ],
  },
  discountPercentage: {
    type: String,
    required() {
      return !this.isConcept;
    },
    default: 0,
  },
  location: {
    type: ObjectId,
    required: true,
    ref: 'Location'
  },
  commissionPercentage: {
    type: Number,
    required: true,
  },
  isConcept: {
    type: Boolean,
    required: true,
    default: false,
  },
  active: {
    type: Boolean,
    default: true,
  },
}, {
  timestamps: true,
});

const Parking = mongoose.model('Parking', parkingSchema);
module.exports = Parking;

请求中的国家/地区和值的值:

console.log('Location', parking.location, typeof parking.location); // Location 5caa0993ab95691762dc1a33 object
console.log('Country', parking.country, typeof parking.country); // Country 5caa04e6b6969a708080f8dd object

所以当我通过Postman发布时:

{
    "name": "Test Parking",
    "reservationsEmail": "example@gmail.com",
    "country": "5caa04e6b6969a708080f8dd",
    "location": "5caa0993ab95691762dc1a33",
    "commission": "20"
}

它的工作方式与预期的一样......虽然通过Fetch API ...

let formData = new URLSearchParams([...new FormData(form).entries()]);

fetch('/parkings/create-concept', {
  method: "POST",
  body: formData,
  credentials: "include",
}).then(response => {
  console.log(response);
}).catch(err => {
  console.log(err);
});
答案

在你的model.js你有这条线吗?

module.exports = mongoose.model('Parking', parkingSchema);

=======================

国家和位置必须是objectId的实例,尝试使用它们进行设置

    mongoose.Types.ObjectId(req.body.myfield);

以上是关于没有生成自动_id的主要内容,如果未能解决你的问题,请参考以下文章

[AndroidStudio]_[初级]_[配置自动完成的代码片段]

[AndroidStudio]_[初级]_[配置自动完成的代码片段]

vscode 用户代码片段 vue初始化模板 Snippet #新加入开头注释 自动生成文件名 开发日期时间等内容

postman 自动生成 curl 代码片段

postman 自动生成 curl 代码片段

VSCode 配置 用户自定义代码片段 自定义自动代码补充