【问题标题】:Mongoosejs update document seems to work, but actually does notMongoosejs 更新文档似乎可以工作,但实际上并没有
【发布时间】:2015-11-05 11:35:37
【问题描述】:

我的 NodeJS 服务器中有以下代码:

Shop.findById(req.params.shopid, function(err, shop) {
    if (err) return res.json(err);
    shop.name = _.extend(shop.name, req.body.name);
    shop.description = _.extend(shop.description, req.body.description);
    shop.social = _.extend(shop.social, req.body.social);
    shop.save(function(err) {
        if (err) return res.json(err);
        return res.json({
            type: true,
            data: shop
        });
    });
});

此代码似乎对象已更新。 返回 res.json({ 类型:真, 资料:店铺 });

但是当我打开数据库或刷新页面时,我面对的是旧数据。

有什么问题?

更新:这是架构

var ShopSchema = new Schema({
name: {
    type: Schema.Types.Mixed,
    default: {}
},
description: {
    type: Schema.Types.Mixed,
    default: {}
},
code: {
    type: String,
    default: shortId.generate()
},
pincode: {
    type: String,
    default: generatePassword(4, false, /\d/)
},
locale: String,
createdAt: {
    type: Date,
    default: Date.now
},
defaultLanguage: {
    type: Schema.ObjectId,
    ref: 'Language'
},
languages: [{
    type: Schema.ObjectId,
    ref: 'Language'
}],
account: {
    type: Schema.ObjectId,
    ref: 'Account'
},
social: {
    facebook: String,
    twitter: String,
    instagram: String,
    foursquare: String,
    website: String
},
images: {
    homepage: String,
    background: String,
    logo: String
},

address: {
    city: String,
    state: String,
    country: String,
    phone: String,
    email: String
}
});

【问题讨论】:

  • 启用猫鼬调试并观察控制台。
  • 每个字段的数据类型是什么?如果它们是数组 mongoose 需要您设置 markModified 以便进行数据库写入。您的响应只是返回您正在制作的对象,而不是回调返回的对象,这就是它“看起来”正在工作的原因。
  • 你能发布架构吗?

标签: node.js mongoose


【解决方案1】:

我开始使用 mongoose-i18n 插件。

var ShopSchema = new Schema({
name: {
    i18n: true,
    type: String
},
description: {
    i18n: true,
    type: String
},
code: {
    type: String,
    default: shortId.generate()
},
pincode: {
    type: String,
    default: generatePassword(4, false, /\d/)
},
locale: String,
createdAt: {
    type: Date,
    default: Date.now
},
defaultLanguage: {
    type: Schema.ObjectId,
    ref: 'Language'
},
languages: [{
    type: Schema.ObjectId,
    ref: 'Language'
}],
account: {
    type: Schema.ObjectId,
    ref: 'Account'
},
social: {
    facebook: String,
    twitter: String,
    instagram: String,
    foursquare: String,
    website: String
},
images: {
    homepage: String,
    background: String,
    logo: String
},

address: {
    city: String,
    state: String,
    country: String,
    phone: String,
    email: String
}
});

现在保存多语言数据不是问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-26
    • 1970-01-01
    • 2018-04-30
    • 2018-01-11
    • 1970-01-01
    • 1970-01-01
    • 2016-03-30
    • 2015-03-03
    相关资源
    最近更新 更多