[英]Mongoose: How do I replace an array of subdocuments?
我已經使用 mongoose 設置了一個用戶架構,其中包含一個子文檔“聯系人”。 子文檔“聯系人”是聯系人對象的集合,其中包含實際聯系人(引用另一個用戶對象)和一些與“友誼”相關的數據。
在我的前端應用程序中,我現在可以通過在我的聯系人列表中添加或刪除用戶來管理聯系人。 前端將這些更改保存為對服務器的 HTTP PUT 請求。
PUT 請求包含整個用戶對象,它或多或少地替換了數據庫上的用戶對象。 不幸的是,無法替換子文檔集合。 您只能推送新的或刪除它們。
以下是架構:
var UserSchema = new Mongoose.Schema({
username: {
type: String,
index: { unique: true, sparse: true },
required: true, lowercase: true, trim: true
},
email: {
type: String,
index: { unique: true, sparse: true },
required: true, lowercase: true, trim: true
},
contacts: [ContactSchema]
});
var ContactSchema = new Mongoose.Schema({
user: {
ref: "User",
type: Mongoose.Schema.ObjectId
},
isContact: {
type: Boolean,
default: true
}
});
目前,我嘗試通過刪除所有聯系人並在請求中添加聯系人來替換聯系人:
app.put('/me', loadUser, function(req, res, next) {
var user = req.user;
req.user.contacts.forEach(function(contact) {
req.body.contacts.forEach(function(contact) {
contact.remove();
});
});
req.body.contacts.forEach(function(contact) {
req.user.contacts.push(contact);
});
user.save(function(err, user) {
if (err) return next(err);
res.send(200);
});
});
有人實際上更好地了解如何將此子文檔集合更新為請求中的狀態嗎?
您可以使用_underscore庫來過濾(拒絕)要刪除的對象
這是一個如何在沒有foreach的情況下從數組中刪除內容的示例。
var _und = require('underscore');
var array = [{_id:1, title:'object one'}, {_id:2, title:'object two'}, {_id:3, title: 'object three' }]
the_target = 'object two';
new_array = _und.reject(array, function(item){
return item.title === target;
})
預期結果應該是:
=> [{_id:1, title:'object one'}, {_id:3, title:'object three'}]
如果你知道id,甚至更好。
所有你需要做的就是通過這樣做清空你的subdocs:
var mytargetarray = [];
mytargetarray.push(new_array);
mytargetarray.save();
如果要替換整個子數組,為什么不直接替換它們:
req.user.contacts = [];
req.user.contacts.push(req.body.contacts);
保存完成。
希望有點幫助。
只是一個提示,在mongodb中你使用對象數組,你可以簡單地替換每個值:
// active data from database
user.name = 'test user';
// now just give the object a new value
user.name = 'new name';
// and save .. done
user.save();
有一個更好的方法使用findOneAndUpdate
來做到這一點。
首先,您為數組中的所有對象(這將是您的子文檔)創建 Mongoose 文檔。 然后使用常規findOneAndUpdate
並替換那里的子文檔數組。 例如:
const subDocumentsArray = argumentArray?.map((object) => new subDocumentModel(object));
const document = await documentModel.findOneAndUpdate(
{ _id: id },
{ subDocumentsArray },
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.