没有自动生成的_id

时间:2019-04-20 11:29:22

标签: node.js express mongoose mongoose-schema

所以我有这段代码用于向数据库添加新项,像这样:

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

所以当我通过邮递员发帖时

{
    "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);
});

1 个答案:

答案 0 :(得分:0)

在您的model.js中,您有这行吗?

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

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

国家和地区必须是objectId的实例,请尝试使用

进行设置
    mongoose.Types.ObjectId(req.body.myfield);