【问题标题】:No automatic _id generated没有自动生成_id
【发布时间】:2019-04-20 20:52:57
【问题描述】:

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

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

【问题讨论】:

    标签: node.js express mongoose mongoose-schema


    【解决方案1】:

    在你的model.js中有你这一行吗?

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

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

    国家和地点必须是objectId的实例,尝试设置它们

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

    【讨论】:

    • 是的,我忘记了。编辑了问题
    • 能否打印出req.body.location和req.body.country的值
    • 你运行的是哪个版本的猫鼬? npm list mongoose,我没有重现错误
    • 您是否在路线文件中导入了停车模型,以及国家和位置?
    • 最新版本:mongoose@5.5.2
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多