无法 post 将 ID 引用给父级 collection mongoDB
Cannot post ref id to parrent collection mongoDB
我正在尝试将两条记录插入 mongoDB。一个是新的 collection 另一个是参考编号。
模式示例
公司{
名称: Acme 公司,
地点:[refID]
}
ID 和位置负载将在请求正文中发送。
addNewLocation: (req, res) => {
let {id, ...payload} = req.body;
db.Location.create(payload)
.then( record => {
let refId = record._id
db.Company.findOneAndUpdate( {_id: id} , { $push: { locations: refId } }, { new: true })
})
.then( result => {
res.status(201).json({success: true},{result})
})
.catch( err => {
res.status(422).json({success: false},{err})
})
}
在查看更新(在 Robo3T 上)时,它似乎正在将文档插入该位置,但它不会在公司 collection 中插入参考 ID。任何想法可能是什么原因造成的?
可能是你在推送 ref 时错误地拼写了位置
它可能是 Locations,因为您的架构字段名称或将架构字段更改为 locations。
你可以在你的公司架构中尝试这个
{
name: String,
locations:[
{
type: Schema.Types.ObjectId,
ref: "Location"
}
]
}
createNewLocation: (req, res) => {
let { companyId , ...payload } = req.body;
db.Location.create(payload)
.then(({_id}) => {
return db.Company.findOneAndUpdate(companyId, {$push:{location: _id}},{new: true})
})
.then(()=>{
res.status(201).json({success: true})
})
.catch((err)=>{
res.status(422).json({success: false})
})
}
这是解决方案,只需要 return。
我正在尝试将两条记录插入 mongoDB。一个是新的 collection 另一个是参考编号。
模式示例 公司{ 名称: Acme 公司, 地点:[refID] }
ID 和位置负载将在请求正文中发送。
addNewLocation: (req, res) => {
let {id, ...payload} = req.body;
db.Location.create(payload)
.then( record => {
let refId = record._id
db.Company.findOneAndUpdate( {_id: id} , { $push: { locations: refId } }, { new: true })
})
.then( result => {
res.status(201).json({success: true},{result})
})
.catch( err => {
res.status(422).json({success: false},{err})
})
}
在查看更新(在 Robo3T 上)时,它似乎正在将文档插入该位置,但它不会在公司 collection 中插入参考 ID。任何想法可能是什么原因造成的?
可能是你在推送 ref 时错误地拼写了位置 它可能是 Locations,因为您的架构字段名称或将架构字段更改为 locations。 你可以在你的公司架构中尝试这个
{
name: String,
locations:[
{
type: Schema.Types.ObjectId,
ref: "Location"
}
]
}
createNewLocation: (req, res) => {
let { companyId , ...payload } = req.body;
db.Location.create(payload)
.then(({_id}) => {
return db.Company.findOneAndUpdate(companyId, {$push:{location: _id}},{new: true})
})
.then(()=>{
res.status(201).json({success: true})
})
.catch((err)=>{
res.status(422).json({success: false})
})
}
这是解决方案,只需要 return。