【问题标题】:How to update subdocument mongoose with NodeJS如何使用 NodeJS 更新子文档猫鼬
【发布时间】:2020-11-23 14:26:15
【问题描述】:
console.log("check")
 
Email.findOneAndUpdate(
    { _id: req.params.idUser, "sendedEmail.emailId": req.params.idEmail},
    { 
        $set: {
            "sendedEmail.$.isSeen": true
        }
    },
    function(error) {
        if (error) {
            console.log(error);
        }
    }
);

var emailList = await Email.find()

res.send(emailList)

它在本地主机上工作正常,但在 vps 中它不会改变任何东西

对不起我的英语不好

【问题讨论】:

  • 你能分享电子邮件的架构吗
  • @MaheshBhatnagar const mongoose = require('mongoose'); var emailSchema = new mongoose.Schema({ subscriberEmail: String, sendedEmail: Array, }, { versionKey: false } ) var Email = mongoose.model('Email', emailSchema, 'emails'); module.exports = Email;

标签: javascript node.js mongodb mongoose


【解决方案1】:

修改这一行:var Email = mongoose.model('Email', emailSchema)。 Mongoose 将创建一个名为:'emails' 的集合

const mongoose = require('mongoose');  
var emailSchema = new mongoose.Schema({     subscriberEmail: String,    sendedEmail: Array,     },     {        versionKey: false     } )  
var Email = mongoose.model('Email', emailSchema); 
module.exports = Email;
用 findById() 方法试试这个语法:

updateEmail: (req, res) => {
        let Id = req.params.id;
        Email.findById(Id, (err, res) =>{
            if(err) return res.status(500).send({message: 'Error to find'});        
        }); 

        let update = req.body;
        Email.findByIdAndUpdate(Id, update, {new: true}, (err, EmailUpdated) => {
            if(err) return res.status(500).send({message: 'Error while updating'});
            if(!EmailUpdated) return res.status(404).send({message: 'Email doesnt exist'});
            return res.status(200).send({email: EmailUpdated});
        });
    },

【讨论】:

  • 它仍然没有改变任何东西,这是我修改后的架构 const mongoose = require('mongoose'); var emailSchema = new mongoose.Schema({ subscriberEmail: String, sendedEmail: Array, }, { versionKey: false } ) var Email = mongoose.model('Email', emailSchema); module.exports = Email;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-11
  • 2012-04-16
  • 1970-01-01
  • 2016-05-24
  • 2020-08-05
相关资源
最近更新 更多