如何更新对象数组中的单个值,并通过其 id 获取数组中的对象以及如何从中获取单个值

问题描述

var agentSchema = new Schema({
    datejoined: Date,Agent: [{
            name: String,phone: String,uniqueid: String,state: String,district: String,fleet: String,payment: String,status: String,hint: String
    
        }],})

这是我的猫鼬数据库代码 我想通过 id 访问对象代理的数组并单独更新付款状态、命中、车队等

 Agent.update({ _id: req.query.person_id }).select({ agent: { $elemmatch: { _id: req.query.object_id } } }).then(



    res.redirect('/admin/agentrequest')).catch(err => console.log(err));

我试图以这种方式获取它,但我无法更新该值

                                           <% for (let doc of prods) { %>
                                            <form method="POST" action="/admin/editbus" class="user">
                                             
                                           

               <div class="form-group row">
                                                    <div class="col-sm-12 mb-3 mb-sm-0">
                                                        <label for="status">status</label>

                                                        <input type="text" name="status" class="form-control form-control-user" list="status" id="exampleFirstName" placeholder="<%= doc.status %>">
                                                        <datalist id="status">
                                                            <option value="Pending">
                                                            <option value="Accepted">
                                                            <option value="Rejected">
                                                            <option value="Waiting for change">
                                                            <option value="Verifying">
                                                          </datalist>

                                                    </div>

                                                </div>
                                                <input type="hidden" name="_id" value="<%= doc._id %>">

                                                <input type="submit" value="change" class="btn btn-primary btn-user btn-block col-sm-12 mb-3 mb-sm-0">

                                                </input>
                                            </form>
                                            <% } %>
                                                <hr>

这是我的 ejs

 Agent.update({ 'agent._id': req.body.id },{
        '$set': {
            'agent.$.phone': req.body.phone,}
    }).then(

        res.redirect('/admin/agentrequest')).catch(err => console.log(err));

我也试过这种方式 在此处输入代码

解决方法

 Agent.findOneAndUpdate({ _id: req.body.agent_id,bus: { $elemMatch: { _id: req.body.object_id } } },{
        $set: {
            'agent.$.phone': req.body.phone,'agent.$.uniqueid': req.body.registration,}
    },// list fields you like to change
    { 'new': true,'safe': true,'upsert': true }).then(

谢谢你,但是这段代码对我有用