MongoDB/Mongoose: On save > Push comment into array, in the array you'll see comment + date

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-25 01:25:48

问题


I have a mongoose model

const clientSchema = mongoose.Schema({

Created: {
    type: String
},

kundnr: {
    type: String,
    unique: true,
    required: true
},

namn: {
    type: String

},

adress: {
    gata: String,
    postkod: Number,
    stad: String
},

kontakt: {
    email: String,
    telefon: Number,
},

company: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Company'
},

notering: [{
    type: String,
}],

lan: [{
    type: String
}]

}, {
timestamps: true
});

module.exports = mongoose.model('Client', clientSchema);

`

and then theres the function

    newClient.kundnr = req.body.kundnr;
    newClient.namn = req.body.namn;
    newClient.adress.gata = req.body.gata;
    newClient.adress.postkod = req.body.postkod;
    newClient.adress.stad = req.body.stad;
    newClient.kontakt.email = req.body.email;
    newClient.kontakt.telefon = req.body.telefon;
    newClient.notering = req.body.notering;

    const save = await newClient.save()

    //redirect
    res.redirect('/newClient');

WHen i save i want to push "notering" into the array, which works. But in the array i want to see both the string + the date it was created/edited.

So when i look in the array i see in position 0 two different things, both the string and the date.

Cant figure out how to do it, maybe shouldnt even use an array but maybe an object instead?


回答1:


For anyone that cares, this is how i solved it.

This is a cutout from my controller.js-file.

exports.updateClientNotering = async (req, res) => {
let id = req.params.id;
let date = new Date();

try {


    const pushNoteringIntoNewClient = await Client.findByIdAndUpdate({
        _id: id
    }, {
        $push: {
            "notering": {
                Author: user.local.name,
                Date: date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate(),
                Notering: req.body.notering
            }
        }
    }, {
        safe: true,
    });


    req.flash('success', "Notering tillagd");
    res.status(200).redirect("back")

} catch (err) {
    return res.status(500).send({
        message: err.message || "Some error occurred while retrieving datas."
    });
};

};

And in the model client.js i define it as such,

notering: [{}],


来源:https://stackoverflow.com/questions/51857894/mongodb-mongoose-on-save-push-comment-into-array-in-the-array-youll-see-com

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!