我正在嘗試通過 Axios 使用 RESTAPI 將專案添加到 MongoDB 陣列中。我認為它看起來類似于 push 方法,但我不知道該怎么做。
我的模型是一個人:
const Schema = mongoose.Schema;
const PersonSchema = new Schema({
name: String,
password: String,
friends: [],
missions: []
})
const personModel = mongoose.model('Person', PersonSchema);
我想在一個人的任務陣列中添加一個任務。
例如,為了添加一個新人,我使用 NodeJS 和 API:(api.js)
router.post('/api/people', (req, res) => {
const personToAdd = req.body;
const newPersonPost = new personModel(personToAdd);
newPersonPost.save((e) => {
if (e) {
console.log("error");
}
});
res.json({
msg: 'Received'
})
});
在客戶端我使用 Axios:
axios({
url: 'http://localhost:8080/api/people',
method: 'POST',
data: dataToUpdate
})
.then(() => {
console.log('axios sent info to server');
}).catch((e) => {
console.log('error' e);
})
太感謝了!
uj5u.com熱心網友回復:
表示
router.post('updating mission endpoint url', async (req, res) =>
try {
const query = { /* content */}; /* write a query to retrieve the concerned user by using a unique identifier */
let person = await personModel.findOne(query);
person.missions.push(req.body.mission);
personModel.save();
} catch (err) {
console.log(err);
}
});
客戶
在客戶端,您只需像上面那樣使用正確的端點 url 將要添加的任務放入資料中,并且應該為要添加任務的用戶添加唯一識別符號。
uj5u.com熱心網友回復:
[]不會將陣列型別分配給您的變數。
使用以下內容更改您的架構檔案:
const Schema = mongoose.Schema;
const PersonSchema = new Schema({
name: { type: String },
password: { type: String },
friends: { type: Array },
missions: { type: Array }
})
uj5u.com熱心網友回復:
使用以下內容更新 db 模型物體檔案
第一種方法:
const Schema = mongoose.Schema;
const PersonSchema = new Schema({
name: String,
password: String,
friends: {type : Array},
missions: {type : Array}
})
const personModel = mongoose.model('Person', PersonSchema);
第二種方法:
const Schema = mongoose.Schema;
const PersonSchema = new Schema({
name: String,
password: String,
friends: [{ type: String }],
missions: [{ type: String }]
})
const personModel = mongoose.model('Person', PersonSchema);
您可以根據需要更新陣列物件。
uj5u.com熱心網友回復:
您只想使用$push更新運算子,非常簡單,如下所示:
db.collection.updateOne(
{
_id: user._id
},
{
"$push": {
"missions": {
mission: newMission
}
}
})
蒙戈游樂場
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/504344.html
