這樣做時,我只是在資料庫中為 list_employee 獲得一個空陣列。那么,是否可以在創建房屋資料庫時推送一個元素?如果不可能,最好在創建后使用 findOneandUpdate 嗎?
這是我的代碼:
module.exports.addHouse = async (req, resp) => {
const {
landLord,
email,
landLordPhone,
address1,
address2,
city,
numEmployees,
state,
zip,
numBeds,
numMattress,
numTables,
preferredName,
firstName,
tenantsPhone,
} = req.body;
console.log(req.body);
try {
const createTenants = await Tenants.create({ preferredName, firstName, tenantsPhone });
const createFacility = await Facility.create({ numBeds, numMattress, numTables });
const createHouse = await House.create({ landLord, email, landLordPhone, address1, address2, city, numEmployees, state, zip, $push: { list_employee: createTenants._id}, facilityInfo: createFacility._id })
resp.status(200).json({house: createHouse});
}catch(e){
console.log(e);
resp.status(200).send('error')
}
}
這是模型:
const houseSchema = new Schema({
landLord: String,
email: String,
landLordPhone: String,
address1: String,
address2: String,
city: String,
numEmployees: String,
state: {
type: String,
},
zip: String,
list_employee: [{
type: mongoose.Schema.ObjectId,
ref: Tenants
}],
facilityInfo: {
type: mongoose.Schema.ObjectId,
ref: Facility
},
// numReports: [{
// type: mongoose.Schema.ObjectId,
// ref: FacilityReports,
// }]
});
const tenantSchema = new Schema({
preferredName: String,
firstName: String,
tenantsPhone: String,
});
uj5u.com熱心網友回復:
嗨,據我了解,諸如$push更新,而不是插入之類的事情。由于您在資料庫中新創建的行上使用 push,因此您不需要使用 push,因為它首先是空的。
看MongoDB Driver API$push是一個陣列更新算子
https://docs.mongodb.com/manual/reference/operator/update/push/
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/406694.html
標籤:
上一篇:查找和更新動態值MongoDB
