【问题标题】:MongoDB/Mongoose: On save > Push comment into array, in the array you'll see comment + dateMongoDB/Mongoose:保存 > 将评论推送到数组中,在数组中你会看到评论 + 日期
【发布时间】:2019-01-22 06:47:47
【问题描述】:

我有一个猫鼬模型

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

当我保存时,我想将“注意”推送到数组中,这很有效。但在数组中,我想同时查看字符串 + 创建/编辑的日期。

所以当我查看数组时,我在位置 0 看到两个不同的东西,字符串和日期。

不知道该怎么做,也许甚至不应该使用数组,而应该使用对象?

【问题讨论】:

  • 没人有答案吗?就像你发布一篇博文一样,你会看到日期、作者和帖子..

标签: arrays mongodb express mongoose mongoose-schema


【解决方案1】:

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

这是从我的 controller.js 文件中截取的。

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 中我这样定义它,

notering: [{}],

【讨论】:

    猜你喜欢
    • 2016-08-09
    • 2019-04-02
    • 2021-12-30
    • 2018-11-22
    • 2018-12-26
    • 2011-12-02
    • 2017-01-17
    • 2020-08-18
    • 1970-01-01
    相关资源
    最近更新 更多