簡體   English   中英

貓鼬模型效果不佳

[英]Mongoose model doesn't work well

這些天來,我正在為一個項目工作,該項目需要使用NodeJS和MongoDB保留一些有關分析的信息。

當我嘗試發送JSon數據時,某些部分已保存到數據庫中,但是大部分數據丟失了。 我不明白我在哪里做錯。 我對這些技術的背景知識不足。

這是我的Mongoose.model;

module.exports = mongoose.model('Products', new Schema({
    unique: Number,
    total: Number,
    hits: {
        String: {
            unique: Number,
            total: Number,
            users:[String]
        }
    }
}));

這是我的創建函數;

var mongoose = require('mongoose'),
    Product = require('../models/products.models')

/**
 * Create a Product
 */
exports.create = function(req, res) {
    var product = new Product(req.body);

    product.save(function(err) {
        if (err)
            return res.status(400);
        else
            res.status(201).json(product);
    });
};

這是我嘗試發布的內容;

{
    "unique" : 50,
    "total" : 150,
    "hits" : {
        "11.06.2015" : {
            "unique" : 50,
            "total" : 60,
            "users" : [ 
                "kris", 
                "mark", 
                "jom", 
                "alpi"
            ]
        },
        "12.06.2015" : {
            "unique" : 50,
            "total" : 90,
            "users" : [ 
                "kris", 
                "mark", 
                "jom"
            ]
        }
    }
}

使用貓鼬Mixed

new Schema({
    unique: Number,
    total: Number,
    hits: {}
}

混合 SchemaType隨處可見,它的靈活性來自於難以維護的折衷。 可以通過Schema.Types.Mixed或通過傳遞空對象文字來使用混合。 以下是等效的:

var Person = new Schema({ any: {} });
var Person = new Schema({ any: Schema.Types.Mixed });

由於它是一種無模式類型,因此您可以將其值更改為您喜歡的任何其他值,但是Mongoose失去了自動檢測/保存這些更改的功能。

要“告訴”貓鼬混合類型的值已更改,請調用文檔的.markModified(path)方法,將路徑傳遞給剛更改的混合類型。

person.anything = { x: [3, 4, { y: "changed" }] };
person.markModified('anything');
person.save(); // anything will now get saved

===============
“貓鼬”:“ ^ 4.0.3”,
mongodb版本v2.6.6

var Product = mongoose.model('Products', new mongoose.Schema({
    unique: Number,
    total: Number,
    hits: {}
}));

var product = new Product({
    "unique" : 50,
    "total" : 150,
    "hits" : {
        "11-06-2015" : {
            "unique" : 50,
            "total" : 60,
            "users" : [
                "kris",
                "mark",
                "jom",
                "alpi"
            ]
        },
        "12-06-2015" : {
            "unique" : 50,
            "total" : 90,
            "users" : [
                "kris",
                "mark",
                "jom"
            ]
        }
    }
});
product.save(function(err,p){
   console.log(err,p);
    Product.find(function(err,p){
        console.log(err,p)
    })
})

它對我來說正常工作。 由於貓鼬拋出錯誤[MongoError: key 12.06.2015 must not contain '.'] ,所以我將12.06.2015更改為12-06-2015

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM