我有 2 個模型:Book 和 Student。我想更新學生模型的書籍陣列中特定書籍的欄位。我怎么能先查詢學生,查詢書籍陣列中的一本書,然后更新書籍物件?
圖書型號:
const bookSchema = new mongoose.Schema({
title:{
type: String
},
length:{
type:Number
},
author:{
type:String
},
ISBN:{
type:String
},
finished:{
type:Boolean
},
dueDate:{
type:String
},
imgURL:{
type:String
}
});
module.exports = mongoose.model("book", bookSchema);
學生模型:
const mongoose = require('mongoose');
const bookSchema = require('./book').schema;
const studentSchema = new mongoose.Schema({
name:{
type: String,
required: true
},
books:{
type: [bookSchema]
}
});
module.exports = mongoose.model("student", studentSchema);```
uj5u.com熱心網友回復:
您可以在 findOneAndUpdate 方法中使用 $set 運算子。
假設您有這個包含兩本書的學生檔案:
{
"_id": "6314eda827c01a07746bceff",
"name": "student 1",
"books": [
{
"_id": "6314eda827c01a07746bcf00",
"title": "book 1 title",
"length": 1,
"author": "book 1 author",
"ISBN": "book 1 ISBN",
"finished": true,
"dueDate": "book 1 dueDate",
"imgURL": "book 1 imgURL"
},
{
"_id": "6314eda827c01a07746bcf01",
"title": "book 2 title",
"length": 2,
"author": "book 2 author",
"ISBN": "book 2 ISBN",
"finished": false,
"dueDate": "book 2 dueDate",
"imgURL": "book 2 imgURL"
}
],
"__v": 0
}
如果我們想用這個 _id 和其中一個書名來更新學生,我們可以這樣做:
app.put('/students/:studentId', async (request, response) => {
const { studentId } = request.params;
const { title, finished } = request.body;
const result = await Student.findOneAndUpdate(
{
_id: new mongoose.Types.ObjectId(studentId),
'books.title': title,
},
{
$set: {
'books.$.finished': finished,
},
},
{
new: true,
}
);
response.send(result);
});
在這里,我在引數中獲取學生 ID,并在請求正文中獲取更新的欄位,您可以根據需要進行更改。
現在如果我們發送一個帶有這個請求正文的請求
{
"title": "book 2 title",
"finished": true
}
結果將是這樣的:(標題為“書 2 書名”的書的已完成屬性更新為 true。
{
"_id": "6314eda827c01a07746bceff",
"name": "student 1",
"books": [
{
"_id": "6314eda827c01a07746bcf00",
"title": "book 1 title",
"length": 1,
"author": "book 1 author",
"ISBN": "book 1 ISBN",
"finished": true,
"dueDate": "book 1 dueDate",
"imgURL": "book 1 imgURL"
},
{
"_id": "6314eda827c01a07746bcf01",
"title": "book 2 title",
"length": 2,
"author": "book 2 author",
"ISBN": "book 2 ISBN",
"finished": true,
"dueDate": "book 2 dueDate",
"imgURL": "book 2 imgURL"
}
],
"__v": 0
}
您可以在請求正文中發送更多欄位并在集合中使用。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/503987.html
上一篇:貓鼬訂單受歡迎程度(按總評分)
下一篇:mongoDB總是更新第一個檔案
