简体   繁体   English

集合未保存在mongodb中(猫鼬填充文档中的故事集合)

[英]Collection isn't being saved in mongodb (Story collection from the mongoose populate documentation)

The below code gives me this error: 下面的代码给我这个错误:

  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")
})

I'm just trying to follow the populate docs . 我只是想遵循填充文档 so I want a solution that goes with that demo. 所以我想要一个与该演示配套的解决方案。 I can't find what im missing. 我找不到我想念的东西。

When I do show collections I only see people and system.indexes collection not stories collection 当我show collections我只会看到people system.indexes收藏集,而不是故事收藏集

EDIT :: I put the following inside the aaron.save() in the else part and I got an error 编辑::我将以下内容放在aaron.save()中的else部分中,但出现错误

{ [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)
                }

            })

I figured that since it said "duplicate" I should drop the database and start the server again and I got the document. 我认为,由于它说“重复”,因此我应该删除数据库并再次启动服务器,然后得到文档。 so that was good. 这样很好。 But I tried to restart the server to save it again and I got a duplicate error again. 但是我尝试重新启动服务器以再次保存它,并且再次出现重复错误。 now I need to drop the collections again. 现在我需要再次删除收藏集。 Why am I getting this duplicate error. 为什么我得到这个重复的错误。 If I just re-save normal docs I don't get this error. 如果我只是重新保存普通文档,则不会出现此错误。

I think this would do the trick. 我认为这可以解决问题。

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")
});

Just check it out and see if it works. 只需检查一下,看看是否可行。

Try my code, it works. 试试我的代码,它可以工作。

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"
        });
    });
});

Basically saving is async. 基本上保存是异步的。 When you are calling Story.findOne the story did not get persisted yet 当您致电Story.findOne时,故事尚未持久

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM