Mongo / Mongoose字段值未更新

时间:2018-03-20 12:11:32

标签: node.js mongodb mongoose

我的MongoDB系列有问题。如果我尝试替换我的项目中的字段,它将不会被保存。它正确记录新值,但DB中没有任何内容真正更改。这有什么不对?

exports.update = function (req, res) {
    const { entryid, userid } = req.params;
    let field;
    ['stop', 'description'].forEach(item => req.query[item] ? field = item : -1);

    db.TimeEntry.findById(entryid).then(function (entry) {
        (req.query[field] === undefined) ? entry[field] = 'no value specified' : entry[field] = req.query[field];
        console.log('v:', entry[field]);

        entry.save(function (err) {
            if (err) console.log(err);

            db.TimeEntry.find({ userId: userid })
                .then(foundEntries => res.status(200).json(foundEntries));
        });
    }).catch(err => console.log(err));
}

架构:

const mongoose = require('mongoose');

const TimeEntrySchema = new mongoose.Schema({
    start: {
        type: mongoose.Schema.Types.Mixed,
        default: Date.now,
        required: true
    },
    stop: mongoose.Schema.Types.Mixed,
    description: String,
    project: String,
    billable: Boolean,
    userId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
        required: true
    }
}, { timestamps: true })

TimeEntrySchema.pre('remove', function (next) {
    User.findById(this.userId).then(user => {
        user.entries.remove(this.id);
        user.save().then(function (e) {
            next();
        }).catch(err => console.log(err));
    })
});

const TimeEntry = mongoose.model('TimeEntry', TimeEntrySchema);
module.exports = TimeEntry;

编辑:以这种方式修改,仍无效果。

` entry[field] = (!req.query[field]) ? 'TESTINGTESTING' : req.query[field];
        entry.markModified('description');

        console.log('v:', entry[field]);

        entry.save().then(function (err) {` 

最终编辑:好的,这是最终解决方案。

exports.update = function (req, res) {
    const { entryid, userid } = req.params;
    let field;
    ['stop', 'description'].forEach(item => req.query[item] ? field = item : -1);

    db.TimeEntry.update({ _id: entryid }, {
        $set: {
            description: req.query[field] || 'no value specified'
        }
    }).then(function () {
        db.TimeEntry.find({ userId: userid })
            .then((foundEntries) => res.status(200).json(foundEntries))
    }).catch(err => console.log(err));
}

2 个答案:

答案 0 :(得分:0)

你试过这个:entry.save().exec(callbackFN); 而不是entry.save(callbackFN);

答案 1 :(得分:0)

尝试使用.update

return db.TimeEntry.update({ _id: entryid }, {
    $set: {
        [field]: req.query[field] || 'no value specified'
    }
  }
}).then(() => db.TimeEntry.find({ _id: entryid }))
  .then((resultEntries) => res.status(200).json(foundEntries))