zoukankan      html  css  js  c++  java
  • Moogoose实践之:Schema写全很重要,不然会把时间浪费在调错上!

    哎,今天浪费了很多时间在调用Moogoose的update函数上,我有一个很简单的文档结构,类似于:{name: xxx},MongoDB的驱动,我用了Moogoose,我的问题是,我想对该文档,增加一个属性,比如age,那么文档就变成:{name: xxx, age: 16}。相关代码如下:

    NameCandidateSchema = new mongoose.Schema(
            name: String
    )
    
        handleVoterVoteFor: (req, res)->
            voter = req.params.voter
            {id} = req.query
    
            query = {_id: id}
            update = {age: 16}
            NameCandidate.findOneAndUpdate(query, update,  (err, doc)=>
                if err then res.send(500, err)
                else
                    console.log(doc)
                    res.json(200, doc)
            )
    

    问题是,age属性死活插入不到文档中去!白白花了2个小时,终于明白了,Schema里面忘记把age属性加进去了。。。汗!

    那么,假如我想加入一个内嵌的文档,但是Key, Value不定,怎么办呢?举个例子,每个name,大家都可以对他投票,投票的记录放在同一个文档中,是一个内嵌的文档,key是投票人的名字,值是他投的票数,比如,对于puncha这个名字,张三、李四分别投了2票3票,那么该文档可以表示成: {name: 'puncha', votes: {'张三': 2, '李四', 3}}。那么Schema怎么定义呢?

    mongoose = require('mongoose');
    Schema = mongoose.Schema;
    
    NameCandidateSchema = new mongoose.Schema(
            name: String
            votes: Schema.Types.Mixed
    )
    
        handleVoterVoteFor: (req, res)->
            #console.log(req.query.name + req.query.id + req.query.score)
            voter = req.params.voter
            {id} = req.query
    
            queryClouse = {_id: id}
            updateClouse = {}
            updateClouse["votes.#{voter}"] = parseInt(score, 10)
            NameCandidate.update(queryClouse, updateClouse,  (err, numberAffected)=>
                if err then res.send(500, err)
                else
                    console.log(numberAffected)
                    res.json(200, numberAffected)
            )
    

    看到没,要使用Schema.Mixed这个类型。BTW, 这里我用了update,其实和上面的findOneAndUpdate是没啥区别的,



  • 相关阅读:
    Linux的inode的理解
    linux中ctrl+z和ctrl+c的区别
    linux后台运行和关闭、查看后台任务
    解决Could not get lock /var/cache/apt/archives/lock
    Spring Boot 2.1.5 正式发布,1.5.x 即将结束使命!
    【免费】某平台16980元编程课程资料下载,仅此1次
    秒杀系统架构分析与实战,一文带你搞懂秒杀架构!
    阿里数据库大牛的 MySQL 学习指南!
    Intellij IDEA 撸码最头大的问题。。
    Java 中的 SPI 机制是什么鬼?高级 Java 必须掌握!
  • 原文地址:https://www.cnblogs.com/puncha/p/3876867.html
Copyright © 2011-2022 走看看