我尝试使用request.body
更新mongoose的子文档,但没有传递子文档_id
。更新工作正常,但mongoose从子文档中删除了_id
。
假设使用以下模式
// schemas.js
const mongoose = require('mongoose');
const motorSchema = new mongoose.Schema({
type: String,
volume: Number,
});
const carSchema = new mongoose.Schema({
manufacturer: String,
model: String,
motors: [motorSchema],
});
const userSchema = new mongoose.Schema({
username: String,
email: String,
cars: [carSchema]
});
const mongoose = require('mongoose');
// import schemas
const userSchema = require('userSchema');
const carSchema = require('carSchema');
const motorSchema = require('motorSchema');
// create models
const User = mongoose.model("User", userSchema);
const Car = mongoose.model("Car", carSchema);
const Motor = mongoose.model("Motor", motorSchema);
module.exports.updateCar = async function (request, response) {
const condition = {
_id: new mongoose.Types.ObjectId(request.body.userId),
"cars._id": new mongoose.Types.ObjectIt(request.body.carId)
};
// Build object for partial update
const set = {};
for(let field in reqest.body){
set[`cars.$.${field}`] = request.body[field];
}
const update = {
$set = set;
}
User.findOneAndUpdate(condition, update, {new: true, overwrite: false},
(error, user) => {
if(error) {response.send(error)}
response.json(user);
}
}
问题是我所有的_id
属性都将在motors数组中被覆盖。我怎样才能强制mongoose作为默认值而不更改_id
属性呢?
1条答案
按热度按时间hvvq6cgz1#
如果我没有理解错的话,等效的mongoDB语法将使用
arrayFilters
,所以您也可以修改查询以使用它:例如:
了解它在playground example上的工作原理
根据此方法,您的代码需要查询的选项部分中的
arrayFilters
和$set
部分中的$[<identifier>]
: