【问题标题】:Collection isn't being saved in mongodb (Story collection from the mongoose populate documentation)集合未保存在 mongodb 中(来自 mongoose 填充文档的故事集合)
【发布时间】:2016-05-07 22:15:37
【问题描述】:

下面的代码给了我这个错误:

  console.log("The creator is %s", story._creator.name)
                                        ^

  TypeError: Cannot read property '_creator' of null

var express = require("express");
var app = express();
var mongoose = require("mongoose");
var Schema = mongoose.Schema;

mongoose.connect("mongodb://localhost/pop2");


var personSchema = Schema({
    _id : Number,
    name : String,
    age : Number,
    stories  : [{type : Schema.Types.ObjectId, ref : "Story"}]
})


var storySchema = Schema({
    _creator : {type : Number, ref : "Person"},
    title : String,
    fans : [{type : Number, ref : "Person"}]
});

var Story = mongoose.model("Story", storySchema);
var Person = mongoose.model("Person", personSchema);


var aaron = new Person({_id : 0, name :"Aaron", age : 100});

aaron.save(function(err){
    if(err) return handleError(err)

    var story1 = new Story({
        title : "Once upon a timex.",
        _creator : aaron._id
    });

    story1.save(function(err){
        if(err) return handleError(err);
        console.log("saved") //doe snot output saved
    })
})

Story.findOne({title : "Once upon a timex."})
        .populate("_creator")
        .exec(function(err, story){
            console.log(story)// I get an output of null in console could be from this
            if(err) return handleError(err);
            console.log("The creator is %s", story._creator.name)}) // error from above



app.listen(3000, function(){
    console.log("listening on 3000")
})

我只是想关注populate docs。所以我想要一个与该演示配套的解决方案。我找不到我缺少的东西。

当我做show collections 时,我只看到peoplesystem.indexes 集合而不是故事集合

编辑 :: 我将以下内容放在 else 部分的 aaron.save() 中,但出现错误

{ [MongoError: insertDocument :: caused by :: 11000 E11000 duplicate key error index: pop2.people.$_id_ dup key: { : 0 }]name: 'MongoError', message: 'insertDocument :: caused by :: 11000 E11000 duplicate key error index

    Story.findOne({title : "Once upon a timex."})
            .populate("_creator")
            .exec(function(err, story){
                // console.log(story)
                if(err) 
                    console.log(err);
                else{
                    console.log("mine : ",story)
                    console.log("The creator is %s", story._creator.name)
                }

            })

我想既然它说“重复”,我应该删除数据库并再次启动服务器,然后我得到了文档。所以那很好。但是我尝试重新启动服务器以再次保存它,但我再次遇到重复错误。现在我需要再次删除收藏。为什么我会收到此重复错误。如果我只是重新保存普通文档,我不会收到此错误。

【问题讨论】:

  • 您是否尝试过:将story1story1.save 保留在aaron.save 之外?它对我有用(但我必须保留一个简单的 handleError 函数)......

标签: javascript mongodb mongoose mongoose-populate database


【解决方案1】:

我认为这样可以解决问题。

var express = require("express");
var app = express();
var mongoose = require("mongoose");
var Schema = mongoose.Schema;

mongoose.connect("mongodb://localhost/pop2");


var personSchema = Schema({
    _id : Number,
    name : String,
    age : Number,
    stories  : [{type : Schema.Types.ObjectId, ref : "Story"}]
})


var storySchema = Schema({
    _creator : {type : Number, ref : "Person"},
    title : String,
    fans : [{type : Number, ref : "Person"}]
});

var Story = mongoose.model("Story", storySchema);
var Person = mongoose.model("Person", personSchema);


var aaron = new Person({_id : 0, name :"Aaron", age : 100});

aaron.save(function(err){
    if(err) return handleError(err)    
});

var story1 = new Story({
    title : "Once upon a timex.",
    _creator : aaron._id
});

story1.save(function(err){
    if(err) return handleError(err);
    console.log("saved")
});

Story.findOne({title : "Once upon a timex."})
        .populate("_creator")
        .exec(function(err, story){
            console.log(story);
            if(err) return handleError(err);
            console.log("The creator is %s", story._creator.name)})



app.listen(3000, function(){
    console.log("listening on 3000")
});

只需检查一下,看看它是否有效。

【讨论】:

  • 感谢您的回答我会尝试的。当您回答时,我自己得到了肯定的结果,但有时我有一个重复的错误。我在对问题的编辑中写到了它。我想知道为什么会出现这个错误。
  • 这看起来可行。仍然想知道为什么在我重新启动服务器后出现重复错误。以及为什么猫鼬文档有错误的信息。我尝试按照演示中的方式进行操作,但没有成功。为什么会这样?无论如何,谢谢。
  • 你用的是哪个版本的猫鼬??
  • 没有猫鼬版……不快递?
  • 其实我也是新手,对此的解决方案纯粹是猜测工作。这个想法来了,通常你保存一件接一件的事情,而不是在回调函数中。很抱歉,我无法就此给您任何建议。
【解决方案2】:

试试我的代码,它可以工作。

var mongoose = require('mongoose')
  , Schema = mongoose.Schema
mongoose.connect('mongodb://localhost/test'); 
var personSchema = new Schema({
  _id     : Number,
  name    : String,
  age     : Number,
  stories : [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});

var storySchema = new Schema({
  _creator : { type: Number, ref: 'Person' },
  title    : String,
  fans     : [{ type: Number, ref: 'Person' }]
});

var Story  = mongoose.model('Story', storySchema);
var Person = mongoose.model('Person', personSchema);

//saving refs
var aaron = new Person({ _id: 0, name: 'Aaron', age: 100 });

aaron.save(function (err) {
  if (err) return handleError(err);

  var story1 = new Story({
    title: "Once upon a timex.",
    _creator: aaron._id    // assign the _id from the person
  });

  story1.save(function (err) {
    if (err) return handleError(err);
    // thats it!
  }).then(function(){
    Story.findOne({ title: 'Once upon a timex.' })
        .populate('_creator')
        .exec(function (err, story) {
        if (err) return handleError(err);
        console.log('The creator is %s', story._creator.name);
        // prints "The creator is Aaron"
        });
    });
});

基本上保存是异步的。当您调用 Story.findOne 时,故事尚未持久化

【讨论】:

    猜你喜欢
    • 2016-02-20
    • 2019-05-26
    • 2020-07-11
    • 2019-08-07
    • 2022-01-07
    • 2017-10-08
    • 2019-01-14
    • 2020-12-05
    • 1970-01-01
    相关资源
    最近更新 更多