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

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

Push value in array of mongodb document

问题

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

  1. module.exports.createroom = async (req, res) => {
  2. const { roomid, email } = req.body;
  3. UserModel.updateOne(
  4. { email: email },
  5. {
  6. $push: { rooms: roomid }
  7. }
  8. )
  9. res.send('done');
  10. }

这段代码会将指定的 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.

  1. module.exports.createroom = async (req,res) => {
  2. const {roomid,email} = req.body;
  3. UserModel.updateOne(
  4. { email: email },
  5. {
  6. $push: { rooms: roomid}
  7. }
  8. )
  9. res.send('done')
  10. }

user schema

  1. const mongoose = require("mongoose")
  2. const userSchema = new mongoose.Schema({
  3. email:{
  4. type:String,
  5. require:true
  6. },
  7. password:{
  8. type:String,
  9. require:true
  10. },
  11. rooms:{
  12. type:Array
  13. }
  14. })
  15. module.exports = mongoose.model("User",userSchema);

correct syntax for updating the record.

答案1

得分: 2

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

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

Make changes in your controller..

  1. module.exports.createroom = async (req,res) => {
  2. const {roomid,email} = req.body;
  3. const user = await UserModel.findOneAndUpdate(
  4. { email : email },
  5. { $push: { rooms: roomid } },
  6. )
  7. res.send("done")
  8. }

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:

确定