首页 > 解决方案 > Mongoose 查找并更新所有

问题描述

所以目前我正在使用这个

await User.findOneAndUpdate({email: req.user.email }, {lastLoad: 'dfConsignee'});

但是我希望能够在提交表单时更新所有具有相同卡车编号的用户。

所以我尝试使用这个

await User.update({truckNumber: truckNumber }, {lastLoad: 'dfConsignee'});

但这只是出于某种原因更新了活动用户。在填写表格时,我将如何更新所有具有相同卡车编号的帐户?

提前谢谢你们<3

编辑 - - - - - - - - - - - - - - - - - - - - - - - - - -------------------------------------------------- -------------------------

活跃用户,我的意思是登录用户。

猫鼬模式:

const mongoose = require('mongoose');

const UserSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true
    },
    password: {
        type: String,
        required: true
    },
    date: {
        type: Date,
        default: Date.now
    },
    isVerified: {
        type: Boolean,
        default: false
    },
    profilePic: {
        type: String,
        default: 'abc'
    },
    truckDriver: {
        type: Boolean,
        default: false
    },
    truckNumber: {
        type: Number
    },
    admin: {
        type: Boolean,
        default: false
    },
    customer: {
        type: Boolean,
        default: false
    },
    loadPlanning: {
        type: Boolean,
        default: false
    },
    lastLoad: {
        type: String,
        default: "dfConsignee"
    }
});

const User = mongoose.model('User', UserSchema);

module.exports = User;

样本文件:

{"_id":{"$oid":"aaaaaaaaaaaaaaaa"},
"isVerified":true,
"profilePic":"abc",
"truckDriver":true,
"admin":false,
"customer":false,
"loadPlanning":false,
"lastLoad":"aAtShipper",
"name":"Nicholas Cage",
"email":"NicholasCage@thegreatestactorever.com",
"password":"password",
"date":{"$date":{"$numberLong":"1580858993547"}},"__v":{"$numberInt":"0"},
"truckNumber":"123",}

为了更清楚一点,当表单提交时,它会拉取登录用户的卡车号码。提交表单后,我希望共享相同卡车编号的每个人也可以更新他们在 lastLoad 中的值。

标签: node.jsmongodbmongoose

解决方案


尝试使用updateMany(). 生成的代码如下所示:

User.updateMany({truckNumber: truckNumber}, {lastLoad: 'dfConsignee'});

如果您真的想全面了解 Mongoose 和 MongoDB,我建议您查看Mongoose 的 API 文档MongoDB 手册,它更详细地介绍了您在使用 MongoDB 时可以使用的工具. 我就是这样找到这个问题的答案的!


推荐阅读