【问题标题】:Edit operation failing in Node编辑操作在节点中失败
【发布时间】:2018-04-20 15:42:07
【问题描述】:

这是我的代码:

router.post('/update-posting', (req, res, next) => {
    Account.findById(req.user._id)
        .then(doc => {
            var type = [];
            if (req.body.full !== undefined) {
                type.push('full');
            }
            if (req.body.part !== undefined) {
                type.push('part');
            }
            if (req.body.seasonal !== undefined) {
                type.push('seasonal');
            }
            if (req.body.temporary !== undefined) {
                type.push('temp');
            }
            var title = req.body.title;
            var salary = req.body.salary;
            var timeline = req.body.timeline;
            var experience = req.body.experience;
            var description = req.body.description;
            var duties = req.body.duties;
            doc.postings[req.body._id] = {
                _id: req.body._id,
                title: title,
                type: type,
                salary: salary,
                timeline: timeline,
                description: description,
                duties: duties,
                experience: experience,
            };
            doc.save(r=>console.log(r));
        })
        .then(() => res.redirect('/employer/booth-edit'))
        .catch(e => console.log(e))
});

这是模型:

var mongoose = require('mongoose');
var plm = require('passport-local-mongoose');
var accountSchema = new mongoose.Schema({
    // username (comes with passport): email; -> just for reference.
    accType: String,
    fullName: String,
    displayName: String,
    companyName: String,
    contactPersonFullName: String,
    companyWebsite: String,
    city: String,
    province: String,
    postalCode: String,
    phoneNumber: String,
    hiringRegion: [], // TODO
    description: String,
    logo: [],
    workingWithEOESC: Boolean,
    industry: String,
    phone: String,
    ageGroup: String,
    education: String,
    lookingForWork: String,
    employmentStatus: String,
    resume: [],
    mainWorkExp: String,
    boothVisits: Number,
    postings: []
});
accountSchema.plugin(plm);
module.exports = mongoose.model('account', accountSchema);

我正在做的是尝试更新帖子数组中的对象。现在这是奇怪的部分。当我控制台记录结果 before doc.save() 我得到了更新的版本......当我控制台记录来自 doc.save() 的响应时,我得到空......我'确定这是一个小错误,但我在任何地方都看不到它。

所有字段都正确来自req.body 对象。

这里是日志。

原始对象:

{ _id: 0,
    title: 'Web developer',
    type: [ 'full', 'seasonal' ],
    salary: '14$',
    timeline: '3 months',
    description: 'tada',
    duties: 'tada',
    experience: '5 years' }

更新的对象:

{ _id: '0',
    title: 'Car mechanic',
    type: [ 'part', 'temp' ],
    salary: '50$',
    timeline: '2 weeks',
    description: 'desc',
    duties: 'resp',
    experience: '4 years' }

doc.save()回复:

null

更有趣的是,这是我用来“创建”招聘信息的代码。几乎是相同的代码,而且运行良好:

router.route('/add-posting')
    .get((req, res, next) => {
        res.render('users/employer/add-posting', {
            title: 'Employer Booth - Add Job Posting',
            user: req.user
        });
    })
    .post((req, res, next) => {
        // Determining type of work.
        var type = [];
        if (req.body.full !== undefined) {
            type.push('full');
        }
        if (req.body.part !== undefined) {
            type.push('part');
        }
        if (req.body.seasonal !== undefined) {
            type.push('seasonal');
        }
        if (req.body.temporary !== undefined) {
            type.push('temp');
        }
        var title = req.body.title;
        var salary = req.body.salary;
        var timeline = req.body.timeline;
        var experience = req.body.experience;
        var description = req.body.description;
        var duties = req.body.duties;

        Account.findById(req.user._id)
            .then(doc => {
                doc.postings.push({
                    _id: doc.postings.length,
                    title: title,
                    type: type,
                    salary: salary,
                    timeline: timeline,
                    description: description,
                    duties: duties,
                    experience: experience,
                });
                doc.save();
            })
            .then(() => res.redirect('/employer/booth-edit'))
            .catch(e => console.log(e));
    });

【问题讨论】:

  • 我认为您的问题可能是您使用了错误的操作。您正在数据库中找到一个对象,然后执行一些操作来操作数据,然后尝试保存该“新”文档。问题是doc.save 调用将失败,因为_id 字段必须是唯一的。您的数据库不知道您正在尝试更新现有文档。它认为您正在尝试插入一个新的。我认为你应该在这里使用的数据库操作是findOneAndUpdate
  • 这很奇怪,因为我使用doc.save() 推送到数组,效果很好。我会更新我的问题
  • 啊,明白了。对于那个很抱歉。我有一段时间没有使用猫鼬了,所以我记错了#save 方法的工作原理。
  • 没问题,你至少试着帮忙了 ;)

标签: javascript node.js mongodb express mongoose


【解决方案1】:

你这样做的方式可能会奏效。但是 mongo 已经为您提供了updatefindOneAndupdate 方法。我建议你使用它们。

您的查询将在需要时易于理解和调试。

试试类似的东西

db.collection.update({_id: .user._id},{$push :{postings:  yourObject}})

【讨论】:

    【解决方案2】:

    我只记得我以前遇到过这个问题。事实证明,要更新数组,我们需要这样做:

    doc.postings.set(req.body._id, {
        _id: req.body._id,
        title: title,
        type: type,
        salary: salary,
        timeline: timeline,
        description: description,
        duties: duties,
        experience: experience,
    });
    

    我记得读过一个关于此的问题。如果我再找到它会添加链接。

    我们需要使用 .set 方法而不是 = 运算符。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-15
      • 2013-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多