Mongoose:在更新后获取文档的新版本



我们有一个MongoDB副本并读取到次要的,在后端我们使用feathersjs与feathersmongoose和文档有一个子文档。在做了一个补丁之后,我们得到旧的子文档。我们已经设置了new: true,也尝试了returnNewDocument: true

const params = {
mongoose: {
new: true
}
}

查看了一下feathers-mongoose的文档,我发现params中的mongoose应该作为mongoose的选项:https://github.com/feathersjs-ecosystem/feathers-mongoose#paramsmongoose

但是子文档仍然是旧的id。子文档有什么特别的事情要做吗?我也对mongoose和mongodb的文档感到困惑,因为mongodb只知道returnNewDocument和mongoose只知道new?

MongoDB: https://docs.mongodb.com/v4.2/reference/method/db.collection.findOneAndUpdate/

猫鼬:https://mongoosejs.com/docs/migration.html findandmodify-new

Schema如下:

const timeSchema = new Schema({
weekday: {
type: Number,
min: 0,
max: 6,
required: true,
},
startTime: { type: Number },
duration: { type: Number },
eventId: { type: String },
room: { type: String },
});
const courseSchema = getUserGroupSchema({
description: { type: String },
startDate: { type: Date },
untilDate: { type: Date },
shareToken: {
type: String,
unique: true,
sparse: true,
},
// here is the reference
times: [timeSchema],
// optional information if this course is a copy from other
isCopyFrom: { type: Schema.Types.ObjectId, default: null },
features: [{ type: String, enum: Object.values(COURSE_FEATURES) }],
...externalSourceSchema,
});

简单。

您可以使用.save()函数来获取更新后的文档。

的例子:

...
let course = await CourseSchema.findById(id); //let's say
if(!course){
throw new Error(...);
}
course.times.weekday = 5;
course.times.startTime = 9;
let updated = course.save();
console.log(updated); // Updated document will be printed.
...

您也可以使用findOneAndUpdate方法。

最新更新