【问题标题】:Mongoose: Get new version of a document after an updateMongoose:更新后获取文档的新版本
【发布时间】:2021-04-25 01:41:30
【问题描述】:

我们有一个 MongoDB 副本并读取到 scondaries,在后端我们使用带有 feathers-mongoose 的feathersjs,并且 Document 有一个 SubDocument。在打了补丁后,我们取回了旧的子文档。我们已经设置了new: true,也尝试了returnNewDocument: true

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

查看 feathers-mongoose 的文档告诉我,参数中的 mongoose 应该作为 mongoose 的选项:https://github.com/feathersjs-ecosystem/feathers-mongoose#paramsmongoose

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

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

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

架构如下:

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,
});

【问题讨论】:

    标签: node.js mongodb mongoose feathersjs mongodb-replica-set


    【解决方案1】:

    简单。

    您可以只使用.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 方法。

    【讨论】:

    • 您好,感谢您的回复,但有两点。 1.不是我自己的代码,目前使用feathers-monogoose,所以无法直接调用model或者schema。我也想过绕过这个,直接连接到 schme,但第一步我想保持这个服务的工作流程。 2. findOneAndUpdate 将返回一个旧的对象,如果没有设置 new 或 returnNewDocument,就像文档中写的那样。我认为feathers-mongoose 在后台执行 findOneAndUpdate 。但是如何传递选项来获取新对象。
    猜你喜欢
    • 2018-12-22
    • 1970-01-01
    • 1970-01-01
    • 2018-09-27
    • 1970-01-01
    • 1970-01-01
    • 2020-07-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多