在MongoDB文档中推送数值到数组中。

huangapple go评论79阅读模式
英文:

Push value in array of mongodb document

问题

你可以使用以下代码来正确更新记录:

module.exports.createroom = async (req, res) => {
    const { roomid, email } = req.body;
    UserModel.updateOne(
        { email: email },
        {
            $push: { rooms: roomid }
        }
    )
    res.send('done');
}

这段代码会将指定的 roomid 添加到具有特定邮箱地址 email 的文档的 rooms 数组中。

英文:

i have one mongodb collection which have documents like these
在MongoDB文档中推送数值到数组中。

now I want to push a value to rooms array of a document where email is abc@123.com ....
I have made this controller in node js.

module.exports.createroom = async (req,res) => {
    const {roomid,email} = req.body;
    UserModel.updateOne(
        { email: email },
        {
          $push: { rooms: roomid}
        }
     )
     res.send('done')
    
}

user schema

const mongoose = require("mongoose")
const userSchema = new mongoose.Schema({
    email:{
        type:String,
        require:true
    },
    password:{
        type:String,
        require:true
    },
    rooms:{
        type:Array
 }

})

module.exports = mongoose.model("User",userSchema);

correct syntax for updating the record.

答案1

得分: 2

对你的控制器进行更改...

module.exports.createroom = async (req, res) => {
  const { roomid, email } = req.body;
  const user = await UserModel.findOneAndUpdate(
    { email: email },
    { $push: { rooms: roomid } },
  );
  res.send("done");
}
英文:

Make changes in your controller..

module.exports.createroom = async (req,res) => {
    const {roomid,email} = req.body;
    const user = await UserModel.findOneAndUpdate(
        { email : email },
        { $push: { rooms: roomid }  },
      )
    res.send("done")
}

huangapple
  • 本文由 发表于 2023年6月12日 16:51:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76454978.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定