MongoDB/猫鼬:保存时>将评论推入数组,在数组中您将看到评论和日期 [英] MongoDB/Mongoose: On save > Push comment into array, in the array you'll see comment + date

查看:116
本文介绍了MongoDB/猫鼬:保存时>将评论推入数组,在数组中您将看到评论和日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有猫鼬模型

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);

`

然后有功能

    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');

当我保存时,我想将"notering"推入数组,这行得通.但是在数组中,我想同时看到字符串和它的创建/编辑日期.

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.

因此,当我查看数组时,我在位置0看到了两个不同的东西,即字符串和日期.

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?

推荐答案

对于任何关心的人,这就是我解决的方法.

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

这是我controller.js文件中的一部分.

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."
    });
};

};

在模型client.js中,我将其定义为

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

notering: [{}],

这篇关于MongoDB/猫鼬:保存时>将评论推入数组,在数组中您将看到评论和日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆