【发布时间】:2020-04-22 12:46:52
【问题描述】:
我有一个名为company 的对象,里面有name(String) 和locations(Array)
在位置内部,我想要一个名为name 的密钥,用户将生成该密钥,第二个密钥是使用ObjectID 生成的。
不幸的是,我无法让它按预期工作。
Example from Postman。请注意,这些位置没有得到_id。
出了什么问题?
我的模型
const mongoose = require('mongoose')
const companySchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
name: String,
locations: [
{
_id: mongoose.Schema.Types.ObjectId,
name: String
}
]
})
module.exports = mongoose.model('Company', companySchema)
我的控制器
createCompany: (req, res) => {
const { name, locations } = req.body
const company = new Company({
_id: new mongoose.Types.ObjectId(),
name: name,
locations: locations
})
company
.save()
.then(() => {
res.status(200).json({
company
})
})
.catch(error => {
res.status(500).json({
error
})
})
},
【问题讨论】:
-
请使用该架构 const companySchema = mongoose.Schema({ _id: mongoose.Schema.Types.ObjectId, name: String, locations: [ { name: String } ] })
-
为什么?我想为每个位置设置 _id。据我所知,我需要它成为架构的一部分..
-
因为在collection中自动定义了id
标签: node.js reactjs mongodb mongoose