英文:
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
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")
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论