【问题标题】:Why can't I save another object in mongoose?为什么我不能在猫鼬中保存另一个对象?
【发布时间】:2016-10-25 14:06:43
【问题描述】:

我正在尝试将用户保存到数据库,但如果它不存在,则创建一个。但它只保存第一个对象(用户)。如果我尝试添加另一个用户,它不想要。有人知道会出现什么问题吗?

型号

var mongoose = require('mongoose');
var uniqueValidator = require('mongoose-unique-validator');
var Schema = mongoose.Schema;

var childSchema = (
    {
        _id: false,
        movieId: {
            type: Number,
            index: true
        },
        value: {
            type: Number
        }
    }
);

var user = new Schema({
    name: {
        type: String
    },
    movieCollections: [childSchema]
});

clickPoint.plugin(integerValidator);
clickPoint.plugin(uniqueValidator);

//export model...
module.exports = mongoose.model("User", user);

控制器:

var User = require('../Models/user');

User.findOne({name: aName}, function (err, data) {
    if(!err) {
        //if data was found
        if(data) {
            console.log('we found somebody');
        }
        else {
            var entry = new User({
                name: aName,
                movieCollections: [{
                    movieId: 12355,
                    value: 23
                }]
            });

            entry.save();
        }
    }
});

【问题讨论】:

    标签: node.js mongodb mongoose mongoose-schema


    【解决方案1】:

    你能尝试显示 entry.save() 的任何错误吗?

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

    编辑

    我认为你必须像这样设置你的架构:

        var childSchema = (
        {
            _id: false,
            movieId: {
                type: Number,
                index: false // Now you can have duplicate movieId
            },
            value: {
                type: Number
            }
        }
    );
    

    希望对你有帮助

    【讨论】:

    • 这是报错 MongoError: E11000 duplicate key error collection: users.user index: movieId_1 dup key: {: null}是movieId变量有问题吗?
    • 我认为这是因为你不能复制你的movieId,如果你需要有重复的movieId,你必须在你的架构中删除你的index:true或设置index:false(检查我的编辑)
    猜你喜欢
    • 2017-04-27
    • 2017-01-04
    • 2014-07-26
    • 2018-07-12
    • 2010-12-04
    • 1970-01-01
    • 2021-06-26
    • 2014-02-10
    • 1970-01-01
    相关资源
    最近更新 更多