首页 > 解决方案 > 按 id 查找但更新子模式

问题描述

所以我用子模式(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.jsexpressmongoosemongoose-schema

解决方案


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

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){ //回调函数 }


推荐阅读