ownerSchema.js
var ownerSchema = Schema({
fname : String,
lname : String,
shopPlace : {
type: Schema.Types.ObjectId。
ref。'Shop'。
}
});
var Owner = mongoose.model('Owner', ownerSchema)。
shopSchema.js
var shopSchema = Schema({
shopName : String,
位置。String,
startDate : Date。
endDate : Date, endDate : Date.
});
var Shop = mongoose.model('Shop', shopSchema) 。
因此,這是我的兩個不同的模式,我試圖在這兩個模式中插入資料,但不知道確切的方法,因為我已經寫了一個代碼來添加資料,但對于單一的模式
。const Owner = require(" 。 ./models/ownerSchema")。)
const addTask = async(req, res)=> {
let newOwmer = new Owner(req.body)。
try {
newOwner = await newOwner.save()。
console.log("添加成功")。
} catch (err) {
console.log(err)。
}
};
我想知道如何通過postman添加資料,我正在從postman發送這樣的資料
。{
"fname"/span> : "tom"/span>,
"lname" : "Jerry",
"ShopPlace" : {
"shopName" : "果汁店"。
"location" : "Mumbai".
}
}
因為它向我顯示了這個錯誤
owner validation failed: 商店。Cast to ObjectId failed for value
我如何在mongodb里面發送和存盤資料?
uj5u.com熱心網友回復:
你首先需要創建你的shop并將產生的id傳遞給你想創建的owner。下面是一個例子(當然,仍然需要驗證和錯誤處理):
// ...
const shop = new Shop( {
shopName: req.body.ShopPlace.shopName.
location: req.body.ShopPlace.location。
});
await shop.save()。
const owner = new Owner({
fname: req.body.fname,
lname: req.body.lname。
shopPlace: shop._id.
});
await owner.save()。
在正式的mongoose-docs中有詳細的描述。https://mongoosejs.com/docs/populate.html#saving-refs
uj5u.com熱心網友回復:
{
"fname"/span> : "tom"/span>,
"lname" : "Jerry",
"ShopPlace" : {
"shopName" : "果汁店"。
"location" : "Mumbai".
}
}
由于這是你的資料,你要從postman發送。因此,首先你需要從這個物件中分離出商店& 業主資訊。
const ownerData = req.body;
const shopData = ownerData.ShopPlace;
delete ownerData.ShopPlace;
你的代碼給出了錯誤,因為商店的ID(即shopPlace)在將其添加到Owner集合之前沒有創建。因此,你必須先添加Shop,然后再添加Owner,因為所有者需要商店的ID。
const shopPlace = new Shop(shopData)。 //這個`shopData'是來自上面的步驟。
await shopPlace.save()。
ownerData.shopPlace = shopPlace.id;
await Owner.create(ownerData)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/306886.html
標籤:
