【问题标题】:Find by id but update subschema按 id 查找但更新子模式
【发布时间】:2022-03-19 15:42:02
【问题描述】:

所以我使用子模式 (allocationAndLocationSchema) 创建了以下模型。每个 MovementSchema 中都会有许多嵌入的 allocationAndLocationSchema。我需要更新各个 allocationAndLocationSchemas 并将它们保存到模型中。

我尝试在子模式上执行 forEach,但更新似乎不起作用。是否有一个简单的解决方案可以通过 id (createdByUserID) 搜索模型并通过 userID 搜索子模式然后更新它的纬度和经度?

模型和子模式:

var allocationAndLocationSchema = new Schema({
    roleID: String,
    roleTitle: String,
    userID: String,
    latitude: String,
    longitude: String,
    lastUpdated: Date
});

var MovementSchema = new Schema({
    dateCreated: Date,
    createdByUserID: String,
    dateEdited: Date,
    allocationAndLocation: [allocationAndLocationSchema]
});

【问题讨论】:

    标签: node.js express mongoose mongoose-schema


    【解决方案1】:

    它只是原始的,所以,从中汲取灵感。

    MovementSchema.findByIdAndUpdate({createdByUserID:req.body.createdByUserID,'allocationAndLocation.userID': req.body.userID},{$set:{allocationAndLocation.$.longitude:req.body.longitude ,allocationAndLocation.$.latitude : req.body.latitude},function(err,res){ //call back function }

    【讨论】:

      猜你喜欢
      • 2018-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多